1

I am tailing lines from a file. And I need to iterate through the output to do some processing.

File Content:

abcd abcd abcd
abcd abcd
abcd abcd
xyz xyz
lmno xvz
pqrs uvw xyz

Below is my snippet that I use.

file=extract.txt
for line in $(tail -n 2 ${file})
do
  echo $line
done

The output that i am expecting is this

lmno xvz
pqrs uvw xyz

The out that I am seeing is this, somehow the white spaces are treated as newline printing each words in single line. Appreciate any help on this. I need to iterate through the actual lines to do some processing.

lmno
xvz
pqrs
uvw
xyz
  • Check https://superuser.com/questions/363559/why-you-dont-read-lines-with-for-in-bash – Diego Torres Milano Feb 07 '23 at 18:24
  • Please read the descriptions of tags before applying them. You can [edit] your Q to fix them. – Ulrich Eckhardt Feb 07 '23 at 18:30
  • See [Bash Pitfalls #1 (for f in $(ls *.mp3))](https://mywiki.wooledge.org/BashPitfalls#for_f_in_.24.28ls_.2A.mp3.29) and [BashFAQ/001 (How can I read a file \(data stream, variable\) line-by-line \(and/or field-by-field)?)](https://mywiki.wooledge.org/BashFAQ/001). – pjh Feb 07 '23 at 22:17
  • Use [Shellcheck](https://www.shellcheck.net/) to find common problems in your shell code. The [Shellcheck](https://www.shellcheck.net/) reports include links to additional information, including fixes. – pjh Feb 07 '23 at 22:18
  • There are a few problems with `echo $line`. `printf '%s\n' "$line"` is good. See [When to wrap quotes around a shell variable?](https://stackoverflow.com/q/10067266/4154375) and the accepted, and excellent, answer to [Why is printf better than echo?](https://unix.stackexchange.com/q/65803/264812). – pjh Feb 07 '23 at 22:21

1 Answers1

2

Use a pipe, not for.

tail -n 2 "$file" | while read -r line
do
    printf "%s\n" "$line"
done

Don't forget to quote your variables so you don't get unexpected word splitting and wildcard expansion.

Barmar
  • 741,623
  • 53
  • 500
  • 612