How to change a specific number in a specific line in a text file?
2 views (last 30 days)
Show older comments
Paige Nardozzo
on 7 Dec 2015
Commented: Guillaume
on 8 Dec 2015
Hi,
I have a txt file and I need to change a specific number in a specific phrase. I want to change the number after the phrase:
UINL_Fuel_C1_Inlet1 56
The number after it as of now is 56 and I want to change it to one of my new values called new_velocity that is calculated in my code. I tried using regexprep but it is not working.
Thanks
1 Comment
Madhu Govindarajan
on 7 Dec 2015
Can you share what you tried? Because if I do something like this for a variable called Random it works fine and I am able to save this back into my text file.
>> Random = regexprep(Random,'UINL_Fuel_C1_Inlet1 56','UINL_Fuel_C1_Inlet1 57')
Accepted Answer
Walter Roberson
on 7 Dec 2015
filecontent = fileread('YourFileNameHere.txt');
newcontent = regexprep(filecontent,'UINL_Fuel_C1_Inlet1 56', sprintf('UINL_Fuel_C1_Inlet1 %g', new_velocity));
fid = fopen('DifferentFileNameHere.txt', 'w');
fwrite(fid, newcontent);
fclose(fid);
2 Comments
Guillaume
on 8 Dec 2015
Note that with arbitrary strings to be replaced it would be much safer to use strrep rather than regexprep, since any character in ([{.+*^$?\| has special meaning for regular expressions.
More Answers (0)
See Also
Categories
Find more on Characters and Strings 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!