regexprep replacing two or more variables in a string of text (once) with ',' between them

3 views (last 30 days)
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
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?

Sign in to comment.

Accepted Answer

Jan
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
mahdi salehzade
mahdi salehzade on 2 Aug 2017
Edited: mahdi salehzade on 2 Aug 2017
yes its my purpose but i want do it buy two value of a function that change every time (get a and b from function and replace them in 4th line). and also your code clear other string of my file , i need to change just 4th line .
Jan
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);

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 2 Aug 2017
Change
b = 'c , d'
to
b = sprintf('%g , %g', c, d)

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!