Home > database >  Linux search subdirectories and among .js .py files for a specific keyword
Linux search subdirectories and among .js .py files for a specific keyword

Time:01-14

I am trying to search for the file/script with a specific keyword in all the sub-directories beginning from the root or home directory. My search yielded so many files, but I want to search only .js, .py types. I want to know the file name containing this matching word.

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

present output:

grep: invalid max count

CodePudding user response:

Here is one way:

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

It will find all .js or .py files in or under the start directory and then grep them for the given word. There's other ways, but this is my "go to" for this type of thing.

CodePudding user response:

You can use the --include option to filter files based on a glob pattern. For multiple globs, you can either use this option multiple times or use the brace expansion feature.

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'

Another option is to make use of globstar feature (assuming you don't have folders that match the globs, or you'll have to use -d skip to prevent directories being treated as files to be searched).

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