[英]Search directory and sub-directories for pattern in a file
In linux, I want to search the given directoy and its sub-folders/files for certain include and exclude pattern.在 linux 中,我想在给定的目录及其子文件夹/文件中搜索某些包含和排除模式。
find /apps -exec grep "performance" -v "warn" {} /dev/null \;
This echoes loads of lines from which search goes trough.这与搜索经过的大量行相呼应。 I don't want that, I'd like to find files containing performance which do not contain warn.
我不希望这样,我想查找包含不包含警告的性能的文件。 How do I do that?
我怎么做?
Very close to what you have already:非常接近您已经拥有的:
find /apps -exec grep "performance" {} /dev/null \; | grep -v "warn"
Just pipe the output through a second call to grep
.只需 pipe 和 output 通过第二次调用
grep
。
To find files containing performance
but not warn
, list the files containing performance
, then filter out the ones that contain warn
.要查找包含
performance
但不包含warn
的文件,请列出包含performance
的文件,然后过滤掉包含warn
的文件。 You need separate calls to grep
for each filter.您需要为每个过滤器单独调用
grep
。 Use the -l
option to grep so that it only prints out file names and not matching lines.对 grep 使用
-l
选项,以便它只打印文件名而不是匹配的行。 Use xargs
to pass the file names from the first pass to the command line of the second-pass grep
.使用
xargs
将第一次传递的文件名传递到第二次传递grep
的命令行。
find /apps -type f -exec grep -l "performance" /dev/null {} + |
sed 's/[[:blank:]\"'\'']/\\&/g' |
xargs grep -lv "warn"
(The sed
call in the middle is there because xargs
expects a weirdly quoted input format that doesn't correspond to what any other command produces.) (中间的
sed
调用在那里,因为xargs
需要一个奇怪的引用输入格式,它与任何其他命令产生的不对应。)
Using -exec
option of the find
command is less effective than pipelining it to xargs
:使用
find
命令的-exec
选项不如将其流水线化到xargs
有效:
find /apps -print0 | xargs -0 grep -n -v "warn" | grep "performance"
This, probably, also solves your problem with printing unwanted output.这可能也解决了您打印不需要的 output 的问题。 You will also probably want tu use the
-name
option to filter out specific files.您可能还希望您使用
-name
选项过滤掉特定文件。
find /apps -name '*.ext' -print0 | xargs -0 grep -n -v "warn" | grep "performance"
If you want to find files that do not contain "warn" at all, grep -v
is not what you want -- that prints all lines not containing "warn" but it will not tell you that the file (as a whole) does not contain "warn"如果您想查找根本不包含“警告”的文件,
grep -v
不是您想要的 - 打印所有不包含“警告”的行,但它不会告诉您文件(作为一个整体)确实不包含“警告”
find /apps -type f -print0 | while read -r -d '' f; do
grep -q performance "$f" && ! grep -q warn "$f" && echo "$f"
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.