0

I am trying to write a script(let's say script1.sh) that find the lines that contain the words that I give, in files that are in a certain directory and its sub directories and only those that are in the files with certain a file extension. So ./script1.sh python py this.is.what.i.look.for should give results like these:

python/abc/file1.py:11:    this.is.what.i.look.for and the line can contain other things as well
python/file2.py:412: this.is.what.i.look.for this.toggleButton.getElement())

I've tried using grep -r to search in the sub directories and managed to find the lines.

grep -r -e $3 $1

gives me the lines but fails to weed out other files with different file extensions and I couldn't find a way to include $2 in the code. Also I failed to put the line numbers in the middle. I tried to split the output into 2 parts like this: python/abc/file1.py: this.is.what.i.look.for and the line can contain other things as well with awk -F " " '{print $1} but couldn't put them back together. I wanted to assign the parts of the output of the grep function into variables and then put them back together but failed at that as well. t1="grep -r -e $3 $1 | awk -F " " '{print $1}'" I tried using " ", ' ' ,$() to assign values since I didn't know which one to use but none of them worked.

  • Does your system's version of grep support a --include glob match option? – steeldriver Nov 23 '19 at 12:26
  • Yes it supports that option – arthionne Nov 23 '19 at 12:30
3

At least with GNU grep, you can use --include (and --exclude) to restrict the matches in a recursive grep, using a shell-style glob expression:

grep -r --include='*.py' -e pattern dir

You can add -n or --line-number to add the numbering. Finally, remember to quote the positional parameters - so

grep -nr --include="*.$2" -e "$3" "$1"
  • I didn't know about the -n and --include. Thank you very much for the explanation. – arthionne Nov 23 '19 at 12:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.