online.0227 online.0227 -4 years ago 93
Bash Question

Different result for reading word by word when there is a new line or not

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download