replacing multiple lines with multiple lines in ascii file
显示 更早的评论
Hi
I would like to make a routine that can replace multiple lines with other multiple lines in a ascii file. This could for example be to replace 7 lines with 4 lines. I can not do it one line at the time because the single lines of the 7 lines are present other places in the file than in the 7 lines.
For single line replacement I have used
fin = fopen('in.txt','r');
fout = fopen('out.txt', 'w+');
while ~feof(fin)
s = fgetl(fin);
s = strrep(s, 'old string', 'newstring');
fprintf(fout,'%s\n',s);
end
fclose(fin);
fclose(fout);
But I can't figure out an easy way to convert this to handle multiple lines replacement.
Do you have any ideas?
Thanks in advance.
Regards Brian.
采纳的回答
更多回答(2 个)
Ken Atwell
2011-5-11
Have you considered regular expressions? the MATLAB function regexprep would probably do the trick:
old_str = [];
rep_str = [];
for i = 1:5
old_str = [ old_str sprintf('Old Line %d\n', i) ];
end
for i = 2:3
rep_str = [ rep_str sprintf('New Line %d\n', i) ];
end
new_str = regexprep(old_str, 'Old Line 2\W+Old Line 3\W+', rep_str);
The '\W+' is a bit of regular expression magic to match one or more whitespace characters, which is why it can span multiple lines.
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!