2013-11-22 34 views
1

假设我有一个文件info.txt。第一列是id,剩下的就是它的内容。迭代Shell中的grep返回的行

1 aaa bbb 
1 ccc ddd mmm 
4 ccc eee 
7 ddd fff jjj kkk 

我只有和以“1”开头的行相关的问题。所以我用grep对其进行过滤:

what_I_concern=$(cat info.txt | grep -iw 1 | cut -d ' ' -f 2-) 

,然后我想通过这些行迭代:

for i in $what_I_concern; do 
    pass $i to another program #I want to pass one line at a time 
done 

但它确实是通过这些线的每一个字迭代,而不是采取每一行作为一个整体。

我该如何解决这个问题?

+0

你照顾有关* *后的数量,所以你不能遍历*每一个*字,但*每第二*,对吗?换一种说法,您希望的输入格式是什么? – Rajish

回答

2

你试图完成你需要的方式是造成分词。相反,说:

while read -r line; do 
    someprogram $(cut -d' ' -f2- <<< "$line") 
done < <(grep '^1' info.txt) 

<()语法被称为Process Substitution。在这种情况下,它使while循环能够将grep命令的输出作为文件读取。

+0

您可以在grep之前解释'<'吗? – duleshi

1

你能避免使用grepcut完全在此情况下(假设默认IFS

while read -r first rest; do 
    [ "$first" = "1" ] && pass "$rest" to another program; 
done < info.txt