2

I have problem on that the program cannot read all words in the file if the file part_Q.txt has no new empty line after last visible line.

part_Q.txt:

NWLR35MQ        649
HCDA93OW        526

*Note that there is no empty line after the line "HCDA93OW 526". The text fully finishes right after 526.

Current output:

word = 'NWLR35MQ'
word = '649'

The strange thing is, if I put one more new line after 526, then my program outputs all 4 words, like below.

Expected output:

word = 'NWLR35MQ'
word = '649'
word = 'HCDA93OW'
word = '526'

Source code:

#!/bin/sh

while read line; do    
    for word in $line; do
        echo "word = '$word'"
    done    
done < part_Q.txt

My question is, how can I output all 4 words without having a new empty line at the end of the file, after 526?

online.0227
  • 640
  • 4
  • 15
  • 29

1 Answers1

1

You can use:

while IFS= read -r line || [[ -n $line ]]; do
   IFS=' '
   for word in $line; do
      echo "word=$word"
   done
done < file

word=NWLR35MQ
word=649
word=HCDA93OW
word=526

Here || [[ -n $line ]] ensures true exit status for while when read fails due to misisng trailing line.

anubhava
  • 761,203
  • 64
  • 569
  • 643