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!