Filter löschen
Filter löschen

Writing a script to take a text file and display the second word in each even numbered row

3 Ansichten (letzte 30 Tage)
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!

Antworten (1)

Bob Thompson
Bob Thompson am 2 Apr. 2019
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.

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by