如何在find的-exec中使用管道 [英] How to use pipe within -exec in find

查看:34
本文介绍了如何在find的-exec中使用管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 find 的 -exec 中使用管道?我不希望 grep 遍历整个文件,而只遍历每个文件的第一行.

Is there any way to use pipe within an -exec in find? I don't want grep to go through whole file, but only through first line of each file.

find /path/to/dir -type f -print -exec grep yourstring {} ;

我尝试用cat"和head -1"将管道放在那里,但效果不佳.我试图以某种方式使用括号,但我没有设法弄清楚如何将它们放在那里.我会非常感谢你的帮助.我知道如何在不使用 find 的情况下以其他方式解决它,但是我们尝试在学校使用 find 和管道来完成它,但无法管理如何去做.

I tried to put the pipelines there with "cat" and "head -1", but it didn't work very well. I tried to use parenthesis somehow, but I didn't manage to work out how exactly to put them there. I would be very thankful for your help. I know how to work it out other way, without using the find, but we tried to do it in school with the usage of find and pipeline, but couldn`t manage how to.

find /path/to/dir -type f -print -exec cat {} | head -1 | grep yourstring ;

这就是我们试图做到的方式,但无法管理括号,甚至可能.我试图通过网络查看,但找不到任何答案.

This is somehow how we tried to do it, but could't manage the parenthesis and wheter it is even possible. I tried to look through net, but couldn' t find any answers.

推荐答案

为了能够使用管道,你需要执行一个shell命令,即带有管道的命令必须是 -exec 的单个命令.

In order to be able to use a pipe, you need to execute a shell command, i.e. the command with the pipeline has to be a single command for -exec.

find /path/to/dir -type f -print -exec sh -c "cat {} | head -1 | grep yourstring" ;

注意以上是猫的无用用法,可以写成:

Note that the above is a Useless Use of Cat, that could be written as:

find /path/to/dir -type f -print -exec sh -c "head -1 {} | grep yourstring" ;

<小时>

实现你想要的另一种方法是说:


Another way to achieve what you want would be to say:

find /path/to/dir -type f -print -exec awk 'NR==1 && /yourstring/' {} ;

这篇关于如何在find的-exec中使用管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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