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

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

问题描述

有没有什么办法可以在find中的-exec中使用管道?我不希望grep通过整个文件,但只能通过每个文件的第一行。

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

我试图用cat和head -1放置管道,但是没有工作得很好。我试图用括号,但我没有设法弄清楚到底怎么把它们放在那里。
我会非常感谢您的帮助。我知道如何用其他方式来解决问题,而不是使用find,但是我们试图在学校里使用find和pipeline来实现,但是不能管理。

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

这是我们怎么做的,但不能管理圆括号甚至可能。我试图通过网络,但无法找到任何答案。
解决方案

为了能够使用管道,你需要执行一个 shell 命令,也就是说,带有管道的命令必须是 -exec 的单个命令。
$ b

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

请注意,以上是 的使用方法,写成:

  find / path / to / dir -type f -print -exec sh -chead -1 { | grep yourstring\; 






另一种达到目标的方法是说:
$ b $ pre $ find / path / to / dir -type f -print -exec awk'NR == 1&& / yourstring /'{} \;


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 {} \;

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.

解决方案

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天全站免登陆