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

2 views (last 30 days)
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 Comment
Christina
Christina on 23 Sep 2011
Correction: in the last command:
line188_changed =strrep(line188,'0.0453, 0.0453, 0.0453, 0.0453',num2str(parameterA))

Sign in to comment.

Accepted Answer

Fangjun Jiang
Fangjun Jiang on 23 Sep 2011
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 Comments
Christina
Christina on 23 Sep 2011
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Data Import and Export in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!