How to change specific number in a specific line in text file?

5 ビュー (過去 30 日間)
ss
ss 2019 年 4 月 25 日
コメント済み: Walter Roberson 2019 年 4 月 30 日
I want to change a specific number in line number (91) from a text file. Line 91 is: a=c+d*1.5. I need to change 1.5 with some other number. But the problem here is 1.5 is not constant, it keeps on changing. So, I want a general code that changes any number instead of 1.5 as well.

回答 (2 件)

Walter Roberson
Walter Roberson 2019 年 4 月 25 日
in_filename = 'YourInputFileNameGoesHere.txt';
out_filename = 'YourOutputFileNameGoesHere.txt';
S = regexp(fileread(in_filename), '\r?\n', 'split');
if isempty(S{end}); S(end) = []; end %regexp often introduces an empty trailing field
S{91} = sprintf('a=c+d*%g', NewValue);
fid = fopen(out_filename, 'wt'); %or 't' instead of 'wt' if you are not using windows
fprintf(fid, '%s\n', S{:});
fclose(fid);
This code might alter the detail of whether the file ends in a newline, or if instead it just ends (either of which are valid for text files.)
It is not recommended that you write to the same output file as your input file: if something were to go wrong then you would have lost the input file. (But if you are sure you can recover from that...)

ss
ss 2019 年 4 月 26 日
Text in line 91 is a=c(d)*1.5 ; i.e. c(d) implies that c as a function of d. I need to keep on changing 1.5 only for multiple times with different values.
  3 件のコメント
ss
ss 2019 年 4 月 26 日
Is there a way to change the text (1.5) by indicating row and column number. Here the row is 91 and column for 1.5 is 7?
Walter Roberson
Walter Roberson 2019 年 4 月 30 日
Where I had
S{91} = sprintf('A=c+d*%g', NewValue);
put
S{row} = [S{row}(1:column-1), sprintf('%g', NewValue)];
This assumes that you want to change to the end of line. If you want to change N characters, then:
S{row} = [S{row}(1:column-1), sprintf('%g', NewValue), S{row}(column+N-1:end)];

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by