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

21 vues (au cours des 30 derniers jours)
Hi,
I have a txt file and I need to change specific numbers in specific lines,
line 131, a = 10
line 132, b = 30
is any way to change the above lines to:
a = 5
b = 60
  2 commentaires
Shahen
Shahen le 1 Juin 2015
I am facing problem in replacing decimal number to integer or new decimal number
for example old a =2.4 and new a= 200 or new a =5.6
I've tried
regexprep(contents, {'a = \f+'}, {sprintf('a = %g', newa)}); the digits after the point are not recognized
Walter Roberson
Walter Roberson le 1 Juin 2015
'\d+' to recognize only decimal digits
'\d+(\.\d*)?' to recognize decimal digits that might optionally be followed by a '.' that in turn might be followed by digits
If the number might be negative, start the pattern with '-?'
If the number might have floating point exponent then it starts to get ugly to write the expression.

Connectez-vous pour commenter.

Réponse acceptée

Walter Roberson
Walter Roberson le 12 Mai 2015
contents = fileread('test.txt');
newa = 10;
newb = 123;
newcontents = regexprep(contents, {'^a\S*=\S*\d+', '^b\S*=\S*\d+'}, {sprintf('a = %d', newa), sprintf('b = %d', newb)});
fid = fopen('test_new.txt', 'wt');
fwrite(fid, newcontents);
fclose(fid);
  4 commentaires
Shahen
Shahen le 13 Mai 2015
{'a = \d+', 'b = \d+'}
Many thanks Walter
100% working
Thiago de Aquino Costa Sousa
Dear community,
I have many txt files that uses a tab delimiter. I have to change the content between the 17th and 18th tab delimiter of all my files. This is one the data inside the file:
_______
Data file generated on Tue Aug 30 12:40:29 2022
A B C D E F G H I J K L M N O P Q R S T U
1 2.00000 2.00000 0.00000 1.00000 28.00000 64.00000 88.00000 1.20000 275.00000 50.00000 30.00000 165.00000 850.00000 500.00000 0.00000 10.00000 10.00000 15.00000 0,0,0,0, 0,0,0,0, false
_______
So I have to change the value for the variable Q (in this case 10.0000) for a specific value. However, some of my files have a different pattern for numbers, instead of 10.00000 it is only 10, what makes the counting characters unfeasible. Furthermore, after some delimiters there are spaces. Then, I decided to count the tab delimeters, and change the content between the 17th and 18th delimiter to solve my problem, that I don't know if it will work. This is my code so far...
ThemeCopy
A = regexp(fileread(myfile), '\n', 'split'); %upload my file to a cell array
B = strfind(A{4}, sprintf('\t')); %takes the cell 4 in the array and finds where I have tab delimiters
C = B{4}(17)+1:B{4}(18)-1; %select the content between the 17th and 18th tab delimiters
Please, can somebody help me???

Connectez-vous pour commenter.

Plus de réponses (2)

Joseph Cheng
Joseph Cheng le 11 Mai 2015
Modifié(e) : Joseph Cheng le 11 Mai 2015
you'll need to use fopen, fgetl, and fprintf() to do this. To accomplish this is that you'll need to open the file in read/write mode and jump to the first specific line (in your example 131) and do your edit by overwriting that line. Then all subsequent lines will have to be rewritten. You cannot just make an edit to the raw file like you would in a text editor. otherwise you'll either end up with additional spaces or lines that are "overlapping".
For example your original line of "a= 10" is say 5 characters long before the new line + carriage return (\n\r). but you want to replace it with "a= 5" which is only 4 characters long. this wouldn't be too big of an issue since you can probably live with an extra " " somewhere. The issue comes in when you are trying to put something like "a= 123" which is longer than the original. Since the inserted text doesn't move all the items below it you'll be writing into the next line's data.
  4 commentaires
Shahen
Shahen le 12 Mai 2015
Modifié(e) : Shahen le 12 Mai 2015
I tried it but I got the same original txt file without any change to the values of a & b
fid = fopen('test.txt');
linenum = 0;
aa=5;
bb=60;
while ~feof(fid)
tline = fgetl(fid);
linenum = linenum+1;
if linenum>=131
if linenum==131
fprintf(fid,'a = %d',aa);
elseif linenum==132
fprintf(fid,'b = %d',bb);
else
fprintf(fid,tline);
end
end
end
fclose(fid);
Walter Roberson
Walter Roberson le 12 Mai 2015
You should always be testing for end of file after you read, not before you read. feof() is not predictive. feof() is not true until you make a read that fails.

Connectez-vous pour commenter.


Thorsten
Thorsten le 12 Mai 2015
Use
patchline('test.txt', 'a = 5', 132)
patchline('test.txt', 'b = 60', 133)
using my function
function patchline(filename, newstring, lineno)
%PATCHLINE
%
%Thorsten.Hansen@psychol.uni-giessen.de
fid1 = fopen(filename, 'r');
if fid1 == -1
error(['Cannot open file ' filename ' for reading.']);
end
tempfilename = 'temp1.txt';
fid2 = fopen(tempfilename, 'w');
if fid2 == -1
error(['Cannot open file ' filename ' for writing.']);
end
line = fgets(fid1);
i = 1;
while line ~= -1
if i == lineno
fprintf(fid2, '%s\n', newstring);
else
fprintf(fid2, '%s', line);
end
line = fgets(fid1);
i = i + 1;
end
st = fclose(fid1);
if st == -1
error(['Cannot close ' filename '.'])
end
st = fclose(fid2);
if st == -1
error(['Cannot close ' tempfilename '.'])
end
if i < lineno
warning(['File ' filename ' has fewer than ' int2str(lineno) 'lines.']);
delete(tempfilename)
else
movefile(tempfilename, filename, 'f')
end
  2 commentaires
Shahen
Shahen le 12 Mai 2015
values of a and b are not fixed (they are changeable according to iteration processes before reading the text file and changing the values of a & b in lines 131 &132), therefore I can't assume a & b as string
Walter Roberson
Walter Roberson le 12 Mai 2015
patchline('test.txt', sprintf('a = %d',a), 132)

Connectez-vous pour commenter.

Catégories

En savoir plus sur Low-Level File I/O dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by