bash grep 仅文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9806944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:49:40  来源:igfitidea点击:

grep only text files

bashgrep

提问by stefcud

find . -type f | xargs file | grep text | cut -d':' -f1 | xargs grep -l "TEXTSEARCH" {}

it's a good solution? for find TEXTSEARCH recursively in only textual files

这是一个很好的解决方案吗?仅在文本文件中递归查找 TEXTSEARCH

回答by kev

You can use the -r(recursive) and -I(ignore binary) options in grep:

您可以在以下位置使用-r(recursive) 和-I(ignore binary) 选项grep

$ grep -rI "TEXTSEARCH" .
  • -IProcess a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-matchoption.
  • -rRead all files under each directory, recursively; this is equivalent to the -d recurseoption.
  • -I处理一个二进制文件,就好像它不包含匹配的数据一样;这相当于--binary-files=without-match选项。
  • -r递归读取每个目录下的所有文件;这相当于-d recurse选项。

回答by user unknown

Another, less elegant solution than kevs, is, to chain -exec commands in find together, without xargs and cut:

另一个不如 kevs 优雅的解决方案是,将 find 中的 -exec 命令链接在一起,而无需 xargs 和 cut:

find . -type f -exec bash -c "file -bi {} | grep -q text" \; -exec grep TEXTSEARCH {} ";" 

回答by Mark B

If you know what the file extension is that you want to search, then a very simple way to search all *.txt files from the current dir, recursively through all subdirs, case insensitive:

如果您知道要搜索的文件扩展名是什么,那么可以通过一种非常简单的方法从当前目录中搜索所有 *.txt 文件,递归遍历所有子目录,不区分大小写:

grep -ri --include=*.txt "sometext" *

grep -ri --include=*.txt "sometext" *