[英]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: 事情是,从第一个sed我得到了我期望的结果,但是从while循环中我没有得到:
./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://mywiki.wooledge.org/ProcessSubstitution
http://wiki.bash-hackers.org/syntax/expansion/proc_subst 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"
. “双引号”是每个包含空格/元字符和每个扩展名的文字:
"$var"
, "$(command "$var")"
, "${array[@]}"
, "a & b"
。 Use 'single quotes'
for code or literal $'s: 'Costs $5 US'
, ssh host 'echo "$HOSTNAME"'
. 使用
'single quotes'
表示代码或使用$'s: 'Costs $5 US'
, ssh host 'echo "$HOSTNAME"'
。 See 看到
http://mywiki.wooledge.org/Quotes http://mywiki.wooledge.org/语录
http://mywiki.wooledge.org/Arguments http://mywiki.wooledge.org/参数
http://wiki.bash-hackers.org/syntax/words http://wiki.bash-hackers.org/syntax/words
I finally found what was going on. 我终于发现发生了什么事。 There was an extra "in" within the while statement.
while语句中有一个额外的“ in”。 Probably I mixed two different kind of whiles.
大概我混合了两种不同的时间。
Where I had: 我在哪里:
while read linea in do echo $linea done < test.tmp 而在读取linea时做回声$ linea done <test.tmp
It should read: 它应显示为:
while read linea; 在阅读linea时; ## in removed and ;
##已删除,且; added do echo $linea done < test.tmp
添加做回声$ linea完成<test.tmp
Thanks again 再次感谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.