Linux在子目录和.js .py文件中搜索特定的关键字

qnakjoqk  于 2023-01-16  发布在  Linux
关注(0)|答案(2)|浏览(189)

我正在尝试在从roothome directory开始的所有子目录中使用特定关键字搜索文件/脚本。我的搜索产生了这么多文件,但我只想搜索.js.py类型。我想知道包含此matching word的文件名。

grep -name '*.js' -rl "matching word" ./

当前输出:

grep: invalid max count
dauxcl2d

dauxcl2d1#

这里有一种方法:

find start_dir -type f \( -name "*.js" -o -name "*.py" \) -exec grep -l "word" {} \;

它会在start目录下找到所有的.js或.py文件,然后用grep搜索给定的单词。还有其他的方法,但这是我对这类事情的“选择”。

8yparm6h

8yparm6h2#

您可以使用--include选项根据glob模式过滤文件。对于多个glob,您可以多次使用此选项或使用大括号扩展功能。

echo --include={*.js,*.py} #expands to: --include=*.js --include=*.py
grep -rl --include={*.js,*.py} 'matching word'

# use this if you can have files that can start with '--include'
grep -rl --include='*.js' --include='*.py' 'matching word'

另一种选择是利用globstar特性(假设您没有与全局对象匹配的文件夹,或者您必须使用-d skip来防止目录被视为要搜索的文件)。

shopt -s globstar
grep -l 'matching word' **/*.js **/*.py

相关问题