25 Feb 2019

Find in files script

Similar to the previous post, I can never remember the correct format for grepping recursively through folders for a particular string. So I added the following script to a file called findinfiles in the scripts directory detailed in the previous post:

1
2
3
4
5
6
#!/bin/bash
if [[ "$2" != "" ]]; then
    grep -inrH --include="$2" $1 .
else
	grep -inrH $1 .
fi

Don’t forget to mark the script as executable of course, and then you can use the script in a couple of ways:

1
2
3
chmod +x findinfiles
findinfiles mystring
findinfiles mystring *.html

The if statement in the script checks for the presence of a second paramater and, if there is one, uses it as an argument to the –include= paramater so that the recursive search is restricted to whatever you pass in, .html files in the example above. If there’s no seond paramater then it searches through all files. It doesn’t follow symlinks, but you can add that option if that’s your preferred default mode of operation.

For someone like me that uses grep and find occasionally, these shortcut scripts are so helpful.

comments powered by Disqus