MATLAB Answers

how to find specific lines in a text file and replace them with other lines?

34 views (last 30 days)
sara kowsar
sara kowsar on 15 Nov 2018
Commented: TADA on 17 Nov 2018
hello everyone...
i have a text file that attached . i want to find some lines that i don't know their position , and replace them with other lines.
lines that i want to remove them are:
*Elset, elset=granulation, generate
1, 8393, 1
** Section: granulation
*Solid Section, elset=granulation, material=granulation
and replace these lines:
*Elset, elset=Element-set1
** Section: Element
*Solid Section, elset=Element-set1, material=Element-num1
Can someone help me ? thanks...

Answers (3)

TADA on 15 Nov 2018
sounds like another job for regular expressions...
text = '';% read your file into this variable
% The pattern is very simple, because you want to replace something super specific
% I just concatenated your lines and replaced white spaces with \s+
pattern = '\*Elset,\s+elset=granulation,\s+generate\s+1,\s+8393,\s+1\s+\*\*\s+Section\:\s+granulation\s+\*Solid\s+Section,\s+elset=granulation,\s+material=granulation';
repText= ['and replace these lines:' newline '*Elset, elset=Element-set1 ' newline ' 1' newline '** Section: Element' newline '*Solid Section, elset=Element-set1, material=Element-num1'];
text1 = regexprep(text, pattern, repText);
TADA on 17 Nov 2018
If you really tried to replace that text with an index with your new text with that index, then again no need to loop through those indexes...
Regular expressions come to the rescue once again:
% read the file
text = fileread('job-1.inp');
%% the regexp split function generates a cell array of strings of before
% after and whats in between the pattern
% We'll also use the tokens function to extract the index of each element
% set
% We're going to join them by adding the element indexing method
pattern = ['\*Elset,\s+elset=granulation,\s+generate\s+1,\s+'...
'(\d+),'... % this matches the 8393 which i assume is a running index 1..8393, parentheses will be used to extract tokens
% First, split using regexp
[splitParts, tokens] = regexp(text, pattern, 'split', 'tokens');
% unravel tokens cell array
i = [tokens{:}];
% if you really wanted to generate a running index instead of extracting it
% i = arrayfun(@num2str,1:length(splitParts)-1,'UniformOutput',false);
% next, generate your indexed element strings:
indexedElementText = strcat(...
'*Elset, elset=Element-set', i, '\n',...
i, ',\n',...
'** Section: ELEMENT_NUMBER_', i, '\n', ...
'*Solid Section, elset=Element-set', i, ...
' , material=Element-', i, '\n,\n');
% finally join the split parts of your file with the indexed elements to
% form your edited file
% and format \n to line breaks
inpupd = sprintf(strjoin(splitParts, indexedElementText));
Matlab offers some powerful text editing functions, However, regular expressions are almost identical in any proggraming language, thats one more reason they are so powerful.

Sign in to comment.

Walter Roberson
Walter Roberson on 15 Nov 2018
For such things, probably the best way is not to use MATLAB, and to instead use a program dedicated to making text changes, such as or or . Each of those languages is designed for sophisticated search and replacement, and can make changes such as you propose a matter of a quite small number of lines of (efficient, compiled) code.
Within MATLAB there are numerous approaches. One of the approaches I am favouring more and more lately is to use fileread() to read the file as text, then use regexprep() to process the file, and then fopen/fwrite/fclose to create the new version. For more sophisticated needs, sometimes it is more appropriate to fileread(), then regexp() with the 'split' option to break it into a cellstr by lines, then use techniques that might include regexp() or regexprep() to locate or modify specific parts, and then afterwards to fopen/fprintf/fclose .

DrZoidberg on 15 Nov 2018
Edited: DrZoidberg on 15 Nov 2018
Hi sara,
I had do to the same once, replace headers in several input scrip files.
This function from Matlab excange server helped me a lot:
% find_and_replace(file, to_find, to_replace)
% Replaces a string (expression) in a given file (file) with a new string
% (replacement).
% See regexprep for info on valid 'expression' and 'replace' inputs.
% Examples:
% Replace all instances of the string 'abs', including 'cabs', with 'mag':
% find_and_replace('my_file.m', 'abs', 'mag');
% Replace all the exact variable names 'my_var' with 'my_other_var'. This
% *won't* match 'my_var_2' or 'this_is_my_var'.
% find_and_replace('my_file.m', '\<my_var\>', 'my_other_var');
% Replace all calls to sqrt(...) with my_sqrt(...), keeping the function's
% argument (this is using regular expressions).
% find_and_replace(tc.file_name, 'sqrt\((.*?)\)', 'my_sqrt\($1\)');
% Note that the above does *not* work for nested parentheses (regular
% expressions can't match nested parentheses to an arbitrary depth).
% This function can also handle multiple files, where the first input is
% either a cell array of file names (e.g., {'file1.txt', 'file2.m'}) or a
% struct with a 'name' field that contains the file name, such as is output
% from files = dir('*.m');
% For example, to replace in all .m files in the current directory:
% find_and_replace(dir('*.m'), 'string_1', 'string_2');
% See doc regexprep for more examples.
% Tucker McClure
% Copyright 2013, The MathWorks, Inc.
Today, there are even more variants of it. With GUI etc.
To understand how it is working, I can recommend to take a look into the documentation of Matlab's regexrep.m and regexp.m

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!