Saturday, March 13, 2021

Linux Find Command with 'or'



On a number of occasions I found it necessary to locate a list of files by extension (e.g. header/source files) and found that if I needed to locate files of multiple extensions I took the 'cowards way out', executing two 'find' commands and appending the results to a temporary output file, then using the output file as input to the next command in the pipeline (e.g. grep).

e.g.

$ find . -type f -name "*.c*" > /tmp/junk

$ find . -type f -name "*.h*" >> /tmp/junk

$ grep -l SetEvent `cat /tmp/junk`


Every single time I do this, one of the voices in my head will mock me in the manner of Monty Python, apparently one of the voices in my head is from medieval France with a talent for hurling insults.


So, today we begin a short journey to the correct way to utilize the 'or' functionality in a Unix find command.



$ find . -type f \( -name "*.c*" -o -name "*.h*" \) -exec grep -l SetEvent {} \;



The above command will locate all header and implementation files (e.g. *.h, *.hpp, *.c, *.cpp...) and return a list of files that contain the SetEvent expression within them. Note the parenthesis are significant to ensure the or'd list is piped to the exec command, otherwise only the second extension list with run through the exec command.


Cheers.

No comments:

Post a Comment