Replacing a string with another string in a text file
Show older comments
My file reads something like this:
"name of unique string"
x= 10, 1, 0, 1, 10
y= 500, 50, 0, 50 500
Now I know how to locate the "name of unique string" BUT what I want to replace is the "y= 500,50,0,50,500".
Can someone help me out with this please?
Thanks in advance, Aniruddh
2 Comments
Geoff Hayes
on 2 Jun 2014
Please post some of the code that you are using to solve this problem. Are you reading in each line of the file and doing some sort of strfind to determine where the unique string is? Do you want to replace only those lines that are y= or just this one in particular?
Aniruddh Matange
on 4 Jun 2014
Accepted Answer
More Answers (1)
... I also know that the "y=" line occurs exactly 4 lines after the "unique string"
while ~feof(fi)
l=fgetl(fi);
if strfind(l,'name of unique string')
for i=1:3, fgetl(fi); end % skip the three intervening
l=fgetl(fi);
% make whatever changes to 'l' need here
...
NB: depending again on what you're trying to do, the above doesn't echo the intervening lines back out to the output file but just discards them...
3 Comments
Aniruddh Matange
on 5 Jun 2014
Aniruddh Matange
on 5 Jun 2014
Edited: Aniruddh Matange
on 5 Jun 2014
dpb
on 5 Jun 2014
As I said in my opening statement, The thing about sequential files is that they're, well..."sequential"
IF and only if the string and it's replacement were of the identical length, then "yes, Virginia, there is a Santa Claus" and you could do the replacement in situ. But, the first restriction is generally too restrictive and even if not the extra effort to write the code to do so is generally counter-productive.
If you want to "edit the original file", then the far simpler way is to use a regular text editor in batch mode.
Categories
Find more on Characters and Strings in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!