Replacing and Inserting a text in an ASCII file

9 views (last 30 days)
How can I insert a text with multiple lines and also replace a text in an ASCII file?

Answers (3)

Jan
Jan on 6 Jun 2011
You can read the file into a string or cell string, perform the operations and write it back again:
Replace in string method:
Str = fileread(FileName);
Str2 = strrep(Str, 'toReplace', 'Replacement');
FID = fopen(FileName, 'w');
if FID < 0, error('Cannot open file'); end
fwrite(FID, Str2, 'uchar');
fclose(FID);
To insert lines in addition:
CStr = regexp(fileread(FileName), char(10), 'split');
CStr2 = strrep(CStr, 'toReplace', 'Replacement');
CStr2 = cat(2, CStr2(1:10), {'Inserted line'}, CStr2(11:end));
FID = fopen(FileName, 'w');
if FID < 0, error('Cannot open file'); end
fprintf(FID, '%s\n', CStr2{:});
fclose(FID);
Care for modern CHAR(10) or DOS style CHAR([13, 10]) linebreaks on demand.

Walter Roberson
Walter Roberson on 5 Jun 2011

Mireia Fontanet
Mireia Fontanet on 28 Dec 2017
Dear, I have two file, the first one is variables.txt and the seconf one is called selector.txt. I want to replace the first line of variables.txt to the 20th line of selector.txt. Then I want to repeat the same but replacinf the second line of variables.txt with the same line of selector.txt. How can I do it?
  1 Comment
Walter Roberson
Walter Roberson on 1 Jan 2018
variables_lines = regexp( fileread('variables.txt'), '\r?\n', 'split');
selector_lines = regexp( fileread('selector.txt'), '\r?\n', 'split');
selector20 = selector_lines{20};
NL = sprintf('\n');
num_variables = length(variables_lines);
outputs = cell(num_variables,1);
for K = 1 : num_variables
temp = variables_lines;
temp{K} = selector20;
outputs{K} = strjoin(temp, NL);
end
Now outputs is a cell array of character vectors, each one being copied from variables.txt but with one line of it replaced with the content of line 20 of selector.txt .
This is probably not the output form you were thinking of, but you said nothing about how you wanted to use the results of the substitution.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!