我在尝试遍历纯文本文件时有一个奇怪的行为:

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

问题是,从第一次sed开始,我得到了我期望的结果,但从while循环中,我没有:
./test.sh
 (5) Sorgo                                              DICOTILEDONEAS                               1,5-2 l/ha          15
(1)
(2)
(3)
(4)
(5)
(6)

我附上这两份文件是为了帮助澄清这里发生的事情:
脚本:https://www.dropbox.com/s/w3sx8zbglvyti7w/test.sh?dl=0
输入数据:https://www.dropbox.com/s/p5jq8dl162jpofv/test.tmp?dl=0
提前谢谢

最佳答案

我会做什么:

#!/bin/bash

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

< <( )是进程替换,检查
http://mywiki.wooledge.org/ProcessSubstitution
http://wiki.bash-hackers.org/syntax/expansion/proc_subst
“双引号”包含空格/元字符的每个文本和每个扩展:"$var""$(command "$var")""${array[@]}""a & b"'single quotes'。对代码或文字使用$'s: 'Costs $5 US'ssh host 'echo "$HOSTNAME"'。见
http://mywiki.wooledge.org/Quotes
http://mywiki.wooledge.org/Arguments
http://wiki.bash-hackers.org/syntax/words

09-10 05:27
查看更多