Replacing a string with another string in a text file
조회 수: 19 (최근 30일)
이전 댓글 표시
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
Geoff Hayes
2014년 6월 2일
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?
채택된 답변
dpb
2014년 6월 2일
The thing about sequential files is that they're, well..."sequential"
You've got a couple of choices -- read the full file as character data and operate in memory to change the 3rd record (determined either by knowing it is the nth record or a search) and then writing the modified memory to a new (or overwrite the existing) file. NB: make backups while testing the latter!!!
Alternatively and for short files probably the easier is to read the file a line at a time, ( fgetl is your friend here) and echoing that line back to a new file until you find the line in question at which time you make the desired change and write the modified record. Then, of course, complete to feof on the file.
fidi=fopen('inputfile','r');
fido=fopen('outputfile','w');
while ~feof(fidi)
l=fgetl(fidi); % read line
if strfind(l,'y=')
% modify line here
l='whatever new string';
end
fprintf(fido,'%s',l) % 'fgetl returns \n so it's embedded
end
fidi=fclose(fidi);
fido=fclose(fido);
Salt to suit...
추가 답변 (1개)
dpb
2014년 6월 4일
편집: dpb
2014년 6월 4일
... 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
dpb
2014년 6월 5일
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.
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!