Replacing a string with another string in a text file
Mostra commenti meno recenti
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 Commenti
Geoff Hayes
il 2 Giu 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
il 4 Giu 2014
Risposta accettata
Più risposte (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 Commenti
Aniruddh Matange
il 5 Giu 2014
Aniruddh Matange
il 5 Giu 2014
Modificato: Aniruddh Matange
il 5 Giu 2014
dpb
il 5 Giu 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.
Categorie
Scopri di più su Characters and Strings in Centro assistenza e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!