0

Let say in a text file if I do

grep FINAL *.msg

it returns

FINAL   COMPUTATIONS:  Elapsed Time: 000:30:55.65; CPU Time: 000:30:26.53  
FINAL   COMPUTATIONS:  Elapsed Time: 000:28:11.77; CPU Time: 000:27:41.36  

Now if I do for loop as

for line in `grep FINAL *.msg`

the "$line" does not consider "FINAL COMPUTATIONS: Elapsed Time: 000:30:55.65; CPU Time: 000:30:26.53" as a single line.

How I can solve this?

steeldriver
  • 81,074
Akand
  • 69

2 Answers2

1

It has to do with the way the shell is splitting your input. Keep in mind that, unless told otherwise, any whitespace will generally split inputs:

$ echo "Foo bar baz"
Foo bar baz
$ for word in $(echo "Foo bar baz"); do echo $word; done
Foo
bar
baz
DopeGhoti
  • 76,081
  • Thanks for your reply. My question, whatever is grep with FINAL (e.g. "FINAL COMPUTATIONS: Elapsed Time: 000:30:55.65; CPU Time: 000:30:26.53"), how I can loop so that $line returns complete line (not FINAL, COMPUTATIONS:, Elapsed, Time, etc. as separate lines)? – Akand Jan 14 '19 at 20:50
1

DopeGhoti is absolutly right, here's something which fits probably a bit more. Read linewise from grep output (pattern applied to all *.msg files in current directory) with help of process subtitution:

i=0; 
while read -r line; do 
    echo $((i++)) "$line"; 
done < <(grep "FINAL" ./*.msg)

snippet is free of shellcheck warnings :)