简体   繁体   中英

How to correctly print read lines in bash

I am having a weird behavior when trying to iterate over a plain text file:

#!/bin/bash
sed -n "5,5p" test.tmp
while read linea in
do 
    echo $linea
done < test.tmp

The thing is that from the first sed I get what I expected, but from the while loop I don't:

./test.sh 
 (5) Sorgo                                              DICOTILEDONEAS                               1,5-2 l/ha          15
(1)
(2)
(3)
(4)
(5)
(6)

I am attaching both files in order to help clarifying what is happening here:

Thanks in advance

What I would do :

#!/bin/bash

while IFS= read -r linea; do 
    printf '%s\n' "$linea"
done < <(sed -n "5,5p" test.tmp)

< <( ) is a process substitution, check
http://mywiki.wooledge.org/ProcessSubstitution
http://wiki.bash-hackers.org/syntax/expansion/proc_subst


"Double quote" every literal that contains spaces/metacharacters and every expansion: "$var" , "$(command "$var")" , "${array[@]}" , "a & b" . Use 'single quotes' for code or literal $'s: 'Costs $5 US' , ssh host 'echo "$HOSTNAME"' . See
http://mywiki.wooledge.org/Quotes
http://mywiki.wooledge.org/Arguments
http://wiki.bash-hackers.org/syntax/words

I finally found what was going on. There was an extra "in" within the while statement. Probably I mixed two different kind of whiles.

Where I had:

while read linea in do echo $linea done < test.tmp

It should read:

while read linea; ## in removed and ; added do echo $linea done < test.tmp

Thanks again

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM