Writing a script to take a text file and display the second word in each even numbered row
조회 수: 3 (최근 30일)
이전 댓글 표시
Would someone be able to help me with a rather simple script I have to write? The script needs to be able to take a text file and display the second word of every even numbered line. Any help is greatly appreciated!
댓글 수: 0
답변 (1개)
Bob Thompson
2019년 4월 2일
One of the simplest ways to do this is by looping through each line with fgetl, and splitting the appropriate lines with regexp. Below is a sample of how to do this.
fid = fopen('mytextfile.txt'); % open the file
fgetl(fid); line = fgetl(fid); % capture the second line
c = 2; % Track line number for troubleshooting
word = []; % initialize blank results array
while ~isnumeric(line);
tmp = regexp(line,'','split'); % split the line by whitespace
word = [word; tmp{1}{2}]; % copy second word onto end of list
fgetl(fid); line = fgetl(fid); % advance to next second line
c = c + 2; % counting lines
end
I have not tested this sample, so there may be some hiccups with a bit of the logic or the indexing. Note that regexp is particularly strange with its indexing, so if tmp{1}{2} returns an error, double check that the indexing is correct before looking to other solutions.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!