필터 지우기
필터 지우기

how to amend an existing text file in a certain line and create new ones

조회 수: 1 (최근 30일)
Hello all
I've got a text file and I need to change only one parameter of it many times (in a for loop).
Until now, I've located the line where my parameter is, I've changed it and NOW I NEED TO WRITE THE NEW PARAMETER IN A NEW TEXT FILE, WHOSE ONLY DIFFERENCE WITH THE PREVIOUS ONE WOULD BE THE DIFFERNT PARAMETER VALUES.
My code until now looks like that.
%Define the range of the parameter sathh
%Assume that sathh can vary between 0.01 and 0.05
parameterA_range = 0.01:0.01:0.05;
%The loop counter
for i=1:length(parameterA_range)
%Extract each value from the range of the parameterA_range
param1 = parameterA_range(i)
%Replicate each of these values 4 times (4 soil layers) and create the new
%parameter set
parameterA = repmat(param1,1,4)
%Replace the parameterA with the new parameterA parameters.
%Open the txt file and scan through it
fid = fopen('sensanalysis3.txt');
C = textscan(fid,'%s','delimiter','\n');
%Find the line number 188, where the parameterA is
line188 = C{1}{188}
line188_changed =strrep(line188,'0.0453, 0.0453, 0.0453, 0.0453',num2str(sathh))
So, in line 188 I need to have the new values of parameterA.
Any ideas?
  댓글 수: 1
Christina
Christina 2011년 9월 23일
Correction: in the last command:
line188_changed =strrep(line188,'0.0453, 0.0453, 0.0453, 0.0453',num2str(parameterA))

댓글을 달려면 로그인하십시오.

채택된 답변

Fangjun Jiang
Fangjun Jiang 2011년 9월 23일
When we manually edit a text file, we can go to a particular line, select the whole line, over-write it with some new text and then save the file.
When using fopen() and fprintf(), we can not really do this over-writing selectively, especially when the number of characters in that line is varying. If the text you are overwriting is always at the same position and the length is the same, you can use fseek() to find the position and then over-write the fixed-length of text.
In your case, the only option is to read the whole file, change the content as needed and then write to a different file. After it is done, you can use delete() and movefile() to delete the old file, rename the new file to the old file name.
  댓글 수: 4
Christina
Christina 2011년 9월 23일
Thanks a lot!
It worked!
The only difference is that I have to type
fprintf(fid_out,'%s\n',C{1}{1:564})
in order to get the whole of the amended text file, not only one line.
Fangjun Jiang
Fangjun Jiang 2011년 9월 23일
Great! FYI, C{1}{:} should be the same as C{1}{1:564}

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 String Parsing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by