regexprep replacing two or more variables in a string of text (once) with ',' between them
3 views (last 30 days)
Show older comments
hi a have bellow code for change an string in my text file
fid = fopen('test.txt','r')
line = 0;
all ={};
while line ~= -1
line = fgets(fid);
if line ~= -1
all = [all;line];
end
end
fclose(fid) ;
buffer = fileread('test.txt') ;
i=4
data = (all{i})
c=300
d= 200
b = 'c , d'
buffer = regexprep(buffer, data,b) ;
fid = fopen('test.txt', 'w') ;
fwrite(fid, buffer) ;
fclose(fid) ;
i want to write c and d both with a ',' between them data (specific line) , but it (regexprep) not accept both of them with that format or i cant use it truly if anyone know how to fix that help! thanks
1 Comment
Jan
on 2 Aug 2017
Please format your code using the "{} Code" button. Currently it is not readable.
You start with a lot code lines to import the file, only to import it again by a single line of code using fileread?
Accepted Answer
Jan
on 2 Aug 2017
What is the purpose of the regexprep call? Is all you want to do to replace the 4.th line of the file by "300 , 200"? Then:
Data = strsplit(fileread('test.txt'), char(10)); % Or TEXTSCAN
Data{4} = sprintf('%g, %g', 300, 200);
fid = fopen('test.txt', 'w');
if fid == -1, error('Cannot open file for writing'); end
fprinft(fid, '%s\n', Data{:});
fclose(fid);
2 Comments
Jan
on 4 Aug 2017
The shown code replaced the 4th line only. Why do you think that other strings are changed also?
If you want to insert two variables, modify the 2nd line:
Data{4} = sprintf('%g, %g', a, b);
More Answers (1)
See Also
Categories
Find more on Data Type Conversion 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!