manipulating text files

I have a .txt file structured as below:
title
name 00xxxx yyyy
name 00xxxx yyyy
in each line the first n characters describe a name, followed by 67-n spaces, then a 6 digit code starting with 2 zeros and after 9 spaces a 4 digit codes. What i need to do is copy the xxxx numbers to the place of the yyyy numbers in all lines of the file and save it back to .txt file by maintaining the exact structure in the output file. How could i handle something like that in matlab ?
Thanks in advance

 채택된 답변

TAB
TAB 2011년 9월 19일

0 개 추천

fi=fopen('YourFile.txt','r');
fo=fopen('outfile.txt','w');
txtcell=textscan(fi,'%s','delimiter','\n');
Str1Idx=1;
Str2Idx=68;
Str3Idx=82;
StrLen=86;
for i=1:length(txtcell{1})
if(length(txtcell{1}{i})==StrLen)
txtcell{1}{i}((Str3Idx):(Str3Idx+4))=txtcell{1}{i}((Str2Idx+2):(Str2Idx+6));
end
fprintf(fo,strcat(txtcell{1}{i},'\n'));
end
fclose(fi);
fclose(fo);

댓글 수: 4

Jan
Jan 2011년 9월 19일
You can get txtcell{1} as separate variable. This is much faster and nicer then accessing the data as nested cell.
conrad Landis
conrad Landis 2011년 9월 19일
it works, but i still have a problem concerning the space delimiters after column no 86. My original document has 159 columns in each line and so i want the output file to be exact the same. By removing strcat from your code i am able to print the 159 columns with whitespaces but i can't manage change line to the output.
TAB
TAB 2011년 9월 19일
Try
fprintf(fo,txtcell{1}{i});
fprintf(fo,'\n');
conrad Landis
conrad Landis 2011년 9월 19일
Thanks it works great although it skips a line. Using fgetl does not skip anything:
inputFile = 'input.txt';
outputFile = 'output.txt';
fi=fopen(inputFile,'r');
fo=fopen(outputFile,'w');
jline=0;
while 1
jline = jline+1;
pretxtcell{jline,:} = fgetl(fi);
if ~ischar(pretxtcell{jline}), break, end
if pretxtcell{jline}==-1, break, end
txtcell{jline,:}=pretxtcell{jline};
if jline>=1
txtcell{jline,1}(1,81:86)=pretxtcell{jline,1}(1,67:72);
end
end
fclose(fi);
for i = 1:size(txtcell,1)
fprintf(fo,txtcell{i,1});
fprintf(fo,'\r\n');
end
fclose(fo);
Anyway, thanks a lot

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

추가 답변 (0개)

카테고리

제품

태그

질문:

2011년 9월 19일

Community Treasure Hunt

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

Start Hunting!

Translated by