dat*_*.io 90 linux search find
经过Google的一些搜索后,我想出的是:
find my_folder -type f -exec grep -l "needle text" {} \; -exec file {} \; | grep text
Run Code Online (Sandbox Code Playgroud)
这是非常不方便的,并输出不需要的文本,如mime类型信息.更好的解决方案?我在同一个文件夹中有很多图像和其他二进制文件,我需要搜索大量文本文件.
cru*_*ore 161
我知道这是一个旧线程,但我偶然发现它,并认为我会分享我的方法,我发现这是一种非常快速的方法,find只用于查找非二进制文件:
find . -type f -exec grep -Iq . {} \; -print
Run Code Online (Sandbox Code Playgroud)
-Igrep 的选项告诉它立即忽略二进制文件,.选项和-q它将使它立即匹配文本文件,因此速度非常快.如果您担心空间,可以将管道更改-print为a 或-print0管道xargs -0(感谢提示,@ lucas.werkmeister!)
第一个点也只是某些BSD版本所必需的,find例如在OS X上,但是如果你想把它放在一个别名或者什么东西中,它不会伤害任何东西.
编辑:正如@ruslan正确指出的那样,-and可以省略,因为它是隐含的.
peo*_*oro 10
为什么不方便?如果你需要经常使用它,并且不想每次只为它定义一个bash函数就输入它:
function findTextInAsciiFiles {
# usage: findTextInAsciiFiles DIRECTORY NEEDLE_TEXT
find "$1" -type f -exec grep -l "$2" {} \; -exec file {} \; | grep text
}
Run Code Online (Sandbox Code Playgroud)
把它放在你的.bashrc,然后运行:
findTextInAsciiFiles your_folder "needle text"
Run Code Online (Sandbox Code Playgroud)
无论你什么时候想要.
编辑以反映OP的编辑:
如果你想要删除mime信息,你可以在管道中添加另一个阶段来过滤掉mime信息.这应该做的伎俩,通过采取只什么来之前::cut -d':' -f1:
function findTextInAsciiFiles {
# usage: findTextInAsciiFiles DIRECTORY NEEDLE_TEXT
find "$1" -type f -exec grep -l "$2" {} \; -exec file {} \; | grep text | cut -d ':' -f1
}
Run Code Online (Sandbox Code Playgroud)
find . -type f -print0 | xargs -0 file | grep -P text | cut -d: -f1 | xargs grep -Pil "search"
Run Code Online (Sandbox Code Playgroud)
不幸的是,这并不节省空间。将其放入 bash 脚本中会更容易一些。
这是空间安全的:
#!/bin/bash
#if [ ! "$1" ] ; then
echo "Usage: $0 <search>";
exit
fi
find . -type f -print0 \
| xargs -0 file \
| grep -P text \
| cut -d: -f1 \
| xargs -i% grep -Pil "$1" "%"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
88294 次 |
| 最近记录: |