Replacing and Inserting a text in an ASCII file
10 次查看(过去 30 天)
显示 更早的评论
How can I insert a text with multiple lines and also replace a text in an ASCII file?
0 个评论
回答(3 个)
Jan
2011-6-6
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.
0 个评论
Mireia Fontanet
2017-12-28
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 个评论
Walter Roberson
2018-1-1
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!