How do i change my script to print out the second word of each even line?

5 views (last 30 days)
fn = input( 'file name: ', 's' );
fh = fopen( fn, 'r' );
ln = '';
count=1;
while ischar( ln )
ln = fgets( fh );
if (ischar( ln ) && mod(count,2)==0)
fprintf( ln );
end
count=count+1;
end
fclose( fh );
I created a script that prints out the even line of a input file but i dont know how to make it print out the second word of each even line.

Accepted Answer

Adam Danz
Adam Danz on 7 Nov 2019
Edited: Adam Danz on 7 Nov 2019
Instead of reading the file line by line you could read in the entire text file and then extract the 2nd word from even numbered lines of the text with just 3 lines of code.
% Read entire file as a char array
C = fileread('MyTextFile.txt');
% Split the char array by line and then split by word.
% ca{j}{m} is the m_th word in the j_th line of text.
ca = cellfun(@strsplit,strtrim(strsplit(C, newline())),'UniformOutput',false);
% get 2nd word of each even numbered line unless the line only has 1 word.
% If the line is empty, it will return an empty.
words = cellfun(@(s)s{min(numel(s),2)},ca(2:2:end),'UniformOutput',false);
% [1]^ [2]^^^^^^^^
% [1] get 2nd word
% [2] isolate even-numbered lines
If you'd rather maintain your fgets method, add the two lines below to display the 2nd word of ln unless it only has 1 word in which case it displays the first word.
lnSplit = strsplit(ln);
fprintf('%s\n',lnSplit{min(numel(lnSplit),2)})
% ^^ Assuming you want a line break
  6 Comments

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!