首先说一下find命令和grep命令的区别:
- 找文件名称含指定词,使用find命令。
- 找文件内容含指定词,使用grep命令。
找文件内容含指定词的三种方法
方法1: 使用grep命令
grep -lR '人无完人' ./
执行man grep命令可以查到-l和-R的功能:
-l, --files-with-matches
Suppress normal output; instead print the name of each input file from which output would normally have been printed. The scanning will stop on the first match.
-R, --dereference-recursive
Read all files under each directory, recursively. Follow all symbolic links, unlike -r.
简言之,-l是用于输出内容含指定词的文件的名称,-R是用于遍历某个路径下的所有文件。
记住命令选项-lR的窍门:
- 窍门一: left and right(左边和右边)的首单词就是lr,根据lr就可以得到lR。
- 窍门二: 把-l理解为list,把-R理解为all,-lR就是list all the files in a path recursively。
# 旧版find命令
find ./ -type f -exec grep -l "人无完人" {} \;
# 新版find命令
find ./ -type f -exec grep -l "人无完人" {}
find ./ -type f -print0 | xargs -0 grep -l '人无完人'