如何 grep 和执行命令(对于每个匹配项) [英] How to grep and execute a command (for every match)
问题描述
如何在一个文件中 grep 并为每个匹配执行一个命令?
How to grep in one file and execute for every match a command?
文件:
foo
bar
42
foo
bar
我想为 foo
上的每个匹配执行例如 date
.
I want to execute to execute for example date
for every match on foo
.
以下尝试不起作用:
grep file foo | date %s.%N
怎么做?
推荐答案
grep file foo | while read line ; do echo "$line" | date %s.%N ; done
在脚本中更易读:
grep file foo | while read line
do
echo "$line" | date %s.%N
done
对于每一行输入,read
会将值放入变量$line
中,while
语句会执行循环体do
和 done
之间.由于该值现在位于变量中而不是标准输入中,因此我使用 echo
将其推回标准输入,但您可以只执行 date %s.%N "$line"
,假设 date 是这样工作的.
For each line of input, read
will put the value into the variable $line
, and the while
statement will execute the loop body between do
and done
. Since the value is now in a variable and not stdin, I've used echo
to push it back into stdin, but you could just do date %s.%N "$line"
, assuming date works that way.
避免在`grep file foo`中使用for line,这很相似,因为
>for
总是在空格处中断,这成为读取文件列表的噩梦:
Avoid using for line in `grep file foo`
which is similar, because for
always breaks on spaces and this becomes a nightmare for reading lists of files:
find . -iname "*blah*.dat" | while read filename; do ....
使用 for
会失败.
这篇关于如何 grep 和执行命令(对于每个匹配项)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!