要查看所有包含“abc”的 php 文件,我可以使用这个简单的脚本:
find . -name "*php" -exec grep -l abc {} \;
我可以省略 -l 并提取部分内容而不是文件名作为结果:
find . -name "*php" -exec grep abc {} \;
我现在想要的是同时执行这两项操作的版本,但在同一行上。
预期输出:
path1/filename1: lorem abc ipsum
path2/filename2: ipsum abc lorem
path3/filename3: non abc quod
或多或少像 grep abc *
那样。
编辑:我想将其用作简单的 shell 脚本。如果输出在一行上就好了,这样就可以进行进一步的 grepping。但是脚本不一定只有一行,反正我把它放在一个 bash 脚本文件中。
编辑 2: 后来我发现了“ack”,这是一个很棒的工具,我现在在大多数情况下都使用它来代替 grep。它能做到这一切,甚至更多。 http://betterthangrep.com/您将编写 ack --php --nogroup abc
以获得所需的结果
最佳答案
使用 -H
开关 ( man grep
):
find . -name "*php" -exec grep -H abc {} \;
替代使用 xargs
(现在不需要 -H
开关,至少对于我这里的 grep
版本是这样):
find . -name "*php" -print | xargs grep abc
编辑:由于 grep
的行为,如 orsogufo 所述,上面的第二个命令应该使用 -H
如果 find
可以想象只返回一个文件名(即如果只有一个 PHP 文件)。如果 orsogufo 的评论 w.r.t. -print0
也并入,命令变为:
find . -name "*php" -print0 | xargs -0 grep -H abc
编辑 2: A(更多1)POSIX Jonathan Leffler 提出的兼容版本,它通过使用 /dev/null
避免了 -H
开关:
find . -name "*php" -print0 | xargs -0 grep abc /dev/null
1:引自opengroup.org manual on find
提示 -print0
是非标准的:
A feature of SVR4's find utility was the -exec primary's + terminator. This allowed filenames containing special characters (especially s) to be grouped together without the problems that occur if such filenames are piped to xargs. Other implementations have added other ways to get around this problem, notably a -print0 primary that wrote filenames with a null byte terminator. This was considered here, but not adopted. Using a null terminator meant that any utility that was going to process find's -print0 output had to add a new option to parse the null terminators it would now be reading.
关于bash - 编写一个 shell 脚本,在 1 行中查找并输出文件名和内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1084266/