I am trying to grep lines matching some pattern and then trying to print those matched lines.
#!/bin/bash
file=/path/to/some/file
pattern=socket
if [ -f $file ]; then
lines=`grep -i "$pattern" $file`
# Case 1
for x in $lines; do # <--- isn't this an array
echo "$x"
done
# Case 2
while read -r line_a; do
echo "$line_a"
done <<< "$lines"
fi
Output:
Case 1: Instead of complete line, individual words from those lines are printed on each new line.
Case 2: Individual lines are printed.
Question:
Why doesn't case 1 print the whole line on one line instead of printing individual words from that line on each new line? Isn't $lines an array of strings (lines in my case) ?
grepas one big string by using backticks. I am guessing the for loop is treating whitespace as the record separator and so each word is treated as an element