I have a txt file in which there are a bunch of lines. The first two lines are shown below:
10125731872 50 3731 -9999 307 166 -9999 827 4090 -9999 587 332 5 -9999
10125731873 50 117 322 9 -9999 187 300 1273 280 103 -9999 39 -9999
I need to add an "M" after all -9999 values. In a text editor this would be simply done by using the replace tool while looking for all "-9999 " and replacing them with "-9999M". Simple! But I have a hard time doing the same thing in Matlab.
Any idea how I can do this simple task?
Thanks.

 채택된 답변

Walter Roberson
Walter Roberson 2020년 8월 12일

1 개 추천

filename = 'a_txt_file.txt';
new_filename = ['new_' filename];
S = fileread(filename);
S = regexprep(S, '-9999\>', '$&M');
fid = fopen(new_filename, 'w');
fwrite(fid, S);
fclose(fid);
It is recommended that new_filename be different than filename: otherwise if something goes wrong in the writing process, you could lose your only copy of the input.

댓글 수: 5

Thanks for the quick answer.
It works, but there is still a small problem. See this is what I got using the syntax you gave me:
10125731872 50 3731 -9999M 307 166 -9999M 827 4090 -9999M 587 332 5 -9999M
10125731873 50 117 322 9 -9999M 187 300 1273 280 103 -9999M 39 -9999M
while this is what I am looking for:
10125731872 50 3731 -9999M 307 166 -9999M 827 4090 -9999M 587 332 5 -9999M
10125731873 50 117 322 9 -9999M 187 300 1273 280 103 -9999M 39 -9999M
Basically, the space that goes after -9999 should be replace with M (rather than just adding an M after -9999 (to keep the formatting of the original txt).
Thanks again.
Okay, I think I found a quick way:
S = regexprep(S, '-9999 \>', '-9999M');
But thanks anyway. It was easy peasy (with the hint you gave me of course)!
Just another point here. The syntax I suggested:
S = regexprep(S, '-9999 \>', '-9999M');
replaces only those -9999 which are in the middle of each line (as they have a space after), but those -9999 at the end of the lines were left out (as they don't have any space after). So once I ran the above regexprep, I had to repeat another one as follows to add M after those -9999 that are the end of each line:
S = regexprep(S, '-9999\>', '-9999M');
Kind of not very neat, but at least it worked. Thanks again for the assistance.
Walter Roberson
Walter Roberson 2020년 8월 12일
편집: Walter Roberson 2020년 8월 12일
regexprep(S, '-9999( |$)', '-9999M', 'lineanchors' )
Kian
Kian 2020년 8월 12일
Thanks a lot. This is really neat!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

kuchina mani chandra
kuchina mani chandra 2023년 4월 3일

0 개 추천

Function replaceStringIntxtFile(filepath,stringToReplace,ReplaceWith) Filedata = readlines(filepath); replacedFiledata =replace(Filedata,stringToReplace,ReplaceWith); F=fopen(filepath,'w'); fprintf(f,'%s\n'replacedFiledata); fclose(f) end

카테고리

도움말 센터File Exchange에서 Variables에 대해 자세히 알아보기

질문:

2020년 8월 12일

답변:

2023년 4월 3일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by