命令在命令行工作,但没有直通脚本
问题描述:
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
, 我得到预期的结果。 我把这个放在循环中,因为我需要一次捕获每条评论,而不是全部。
答
这是因为通过每个字在$result
for x in $result
将循环 - 这就是for
的意思做。
试试这个:
echo "$result" | while read x; do
echo "$x"
done
read
将采取一行的时间,这是什么您这里需要。
答
您的问题不是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
gotcha,感谢您的代码。 – phani 2012-07-06 14:45:47
使用bash,你可以使用here-string:'read line; ...;完成 2012-07-06 19:44:59