Replacing a string with another string in a text file
Mostrar comentarios más antiguos
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 comentarios
Geoff Hayes
el 2 de Jun. de 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
el 4 de Jun. de 2014
Respuesta aceptada
Más respuestas (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 comentarios
Aniruddh Matange
el 5 de Jun. de 2014
Aniruddh Matange
el 5 de Jun. de 2014
Editada: Aniruddh Matange
el 5 de Jun. de 2014
dpb
el 5 de Jun. de 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.
Categorías
Más información sobre Characters and Strings en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!