命令在命令行工作,但没有直通脚本

问题描述:

cat test.txt 
#this is comment 
line 1 
line 2 
#this is comment at line 3 
line4 

脚本:命令在命令行工作,但没有直通脚本

预期输出:

#this is comment 
#this is comment at line 3 

获得输出:

#this 
is 
comment 
#this 
is 
comment 
at 
line 
3 

但是当我执行此命令awk '/^#.*/ { print }' test.txt, 我得到预期的结果。 我把这个放在循环中,因为我需要一次捕获每条评论,而不是全部。

这是因为通过每个$resultfor x in $result将循环 - 这就是for的意思做。

试试这个:

echo "$result" | while read x; do 
    echo "$x" 
done 

read将采取一行的时间,这是什么您这里需要。

+0

gotcha,感谢您的代码。 – phani 2012-07-06 14:45:47

+1

使用bash,你可以使用here-string:'read line; ...;完成 2012-07-06 19:44:59

您的问题不是awk部分,而是for部分。当你做

for x in yes no maybe why not 
do 
    echo x 
done 

你会得到

yes 
no 
maybe 
why 
not 

也就是说,for被遍历列表会自动为空格分隔。

我想一个解决方法是用引号包装注释;那么for将把每个引用的注释视为单个项目。 legoscia的修复(在一个while循环中使用read)对我来说似乎更好。

+0

你是对的,我错过了循环的基本逻辑。 – phani 2012-07-06 14:46:33