Modify a text file
5 次查看(过去 30 天)
显示 更早的评论
Hello,
I want to open an existing text file, replace the number of "4.500000e-001" in the third column from line06 to line16 to another number (for example, 0.8), save the file.
The number in the third column may have different values.
Any help appreciated
Best regards!
LINE01: MDF=4
LINE02: 8
LINE03: 1 0.000000e+000 1.000000e+000 1.000000e+000 1.000000e+000
LINE04: 2 -1.000000e+002 1.000000e+000 1.000000e+000 6.000000e+000
LINE05: 16 88 99 1 x temp mech snow alt sol emb ooo rrr rdr iut
LINE06: 1 -0.000000e+000 4.500000e-001 1 1 0.000000e+000 1.000000e+000 1.000000e+000 1.000000e+000
LINE07: 2 -1.000000e+000 4.500000e-001 1 1 0.000000e+000 1.000000e+000 1.000000e+000 1.000000e+000
LINE08: 3 -2.000000e+000 4.500000e-001 1 1 0.000000e+000 1.000000e+000 1.000000e+000 1.000000e+000
LINE09: 4 -3.000000e+000 4.500000e-001 1 1 0.000000e+000 1.000000e+000 1.000000e+000 1.000000e+000
LINE10: 5 -4.000000e+000 4.500000e-001 1 1 0.000000e+000 1.000000e+000 1.000000e+000 1.000000e+000
LINE11: 6 -5.000000e+000 4.500000e-001 1 1 0.000000e+000 1.000000e+000 1.000000e+000 1.000000e+000
LINE12: 7 -6.000000e+000 4.500000e-001 1 1 0.000000e+000 1.000000e+000 1.000000e+000 1.000000e+000
LINE13: 8 -7.000000e+000 4.500000e-001 1 1 0.000000e+000 1.000000e+000 1.000000e+000 1.000000e+000
LINE14: 9 -8.000000e+000 4.500000e-001 1 1 0.000000e+000 1.000000e+000 1.000000e+000 1.000000e+000
LINE15: 10 -9.000000e+000 4.500000e-001 1 1 0.000000e+000 1.000000e+000 1.000000e+000 1.000000e+000
LINE16: 11 -1.000000e+001 4.500000e-001 1 1 0.000000e+000 1.000000e+000 1.000000e+000 1.000000e+000
LINE17: 6
LINE18: 11 31 41 61 81 98
0 个评论
回答(1 个)
Chunru
2021-11-17
% Assume that your text file is data.txt
s = fileread("data.txt");
s = strrep(s, '4.500000e-001', '0.8000');
fid = fopen('data1.txt', 'wt');
fprintf(fid, '%s', s);
fclose(fid);
type data1.txt
1 个评论
Rik
2021-11-17
Note that fileread might not properly deal with UTF-8. That is probably not relevant in this case (as fopen should only default to UTF-8 in cases where fileread correctly deals with it), but it is something you should be aware of.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!