有什么办法可以在find中使用pipe道内的-exec吗? 我不希望grep通过整个文件,但只能通过每个文件的第一行。
find /path/to/dir -type f -print -exec grep yourstring {} \;
我试着用“猫”和“头-1”把pipe道放在那里,但是效果不好。 我试图用括号,但我没有设法弄清楚到底怎么把它们放在那里。 我会非常感谢你的帮助。 我知道如何用其他方式来解决问题,而不是使用find,但是我们试图在学校里使用find和pipeline来实现,但是不能pipe理。
find /path/to/dir -type f -print -exec cat {} | head -1 | grep yourstring \;
这是我们试图做到的,但不能pipe理括号,甚至是可能的。 我试图通过networking,但无法find任何答案。
为了能够使用管道,你需要执行一个shell命令,即带有管道的命令必须是一个单一的命令-exec
。
find /path/to/dir -type f -print -exec sh -c "cat {} | head -1 | grep yourstring" \;
请注意,上面是一个无用的猫 ,可以写成:
find /path/to/dir -type f -print -exec sh -c "head -1 {} | grep yourstring" \;
实现你想要的另一种方法是说:
find /path/to/dir -type f -print -exec awk 'NR==1 && /yourstring/' {} \;
这不会直接回答你的问题,但是如果你想做一些复杂的操作,你可能会更好的脚本:
for file in $(find /path/to/dir -type f); do echo ${file}; cat $file | head -1 | grep yourstring; done