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
  • 78,509
  • 12
  • 109
  • 152
Akand
  • 69
  • 2
  • 9
  • 1
    Related, I think: [Reading lines from a file with bash: for vs. while](https://unix.stackexchange.com/questions/24260/reading-lines-from-a-file-with-bash-for-vs-while) – steeldriver Jan 14 '19 at 20:27
  • Your question reads to me like this could very well be a form of "XY Problem" (see: https://en.wikipedia.org/wiki/XY_problem). Please edit your question to show exactly what it is you are trying to _accomplish_ with your input data. – DopeGhoti Jan 14 '19 at 21:12

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
  • 73,792
  • 8
  • 97
  • 133
  • 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 :)