如何grep和执行一个命令(对于每一场比赛) [英] How to grep and execute a command (for every match)

查看:90
本文介绍了如何grep和执行一个命令(对于每一场比赛)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在一个文件中grep并为每个匹配执行一个命令?

文件:

  foo 
bar
42
foo
bar

我想为 foo 中的每个匹配执行例如 date



以下尝试不起作用:

  grep file foo |日期%s。%N 

如何做?

解决方案

  grep file foo |而读线;做回声$行|日期%s。%N;完成

在脚本中可读性更强:

  grep file foo |而读行

echo$ line|日期%s。%N
完成

对于每一行输入, read 会将值放入变量 $ line 中,并且同时语句将在 do done 之间执行循环体。由于该值现在是一个变量,而不是标准输入,因此我使用 echo 将其重新转换为标准输入,但是您可以只执行日期% s。%N$ line,假设日期是这样的。

避免在`grep中使用文件foo` 类似,因为对于总是在空格上出现断裂,这对于读取文件列表来说是一场噩梦:

  find。 -iname* blah * .dat|同时读取文件名; do .... 

会因为而失败


How to grep in one file and execute for every match a command?

File:

foo
bar
42
foo
bar

I want to execute to execute for example date for every match on foo.

Following try doesn't work:

grep file foo | date %s.%N

How to do that?

解决方案

grep file foo | while read line ; do echo "$line" | date %s.%N ; done

More readably in a script:

grep file foo | while read line
do
    echo "$line" | date %s.%N
done

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.

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 ....

would fail with for.

这篇关于如何grep和执行一个命令(对于每一场比赛)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆