Find all the files that don’t have a specific line in them, or How I learned to stop worrying and love Linux
Monday, June 16th, 2008So at my dayjob, we often have to do some funky things. Like today, we are doing a refactor, and we wanted to know whether any of our web templates don’t use a component, because we needed to add something to it that would be global, and anything that didn’t use it would need to have our lines manually added.
With over 200 templates to look through this was looking like a pain to do, howver, in about 5 minutes, me and my pair managed to develop three solutions using just bash scripting.
My first was:
find . -iname \*.vm -exec bash -c "grep -Hiq javascript.vm {} || echo Not Found in {}" \;
While doing this, I was looking for the -q option on grep, to keep grep quiet when finding the files, and I found the -L option which does almost exactly this:
find . -iname \*.vm -exec grep -L javascript.vm {} \;
The -L says print the filename that didn’t match the expression on any of it’s lines. (For the record, -l does the inverse, so finding all templates which contain a line is also easy). Meanwhile Patric found a nice solution too,
find . -iname \*.vm -! -exec grep -q javascript.vm {} \; -print
This also relies on the return value of grep, but instead of some funky bash logic, uses find’s built in operators to execute the -print if the -exec returns 1
Did I say how much I like linux?