exec


Execute a command on the results of a search with the find command 1

find $LOCATION -name "$FILENAME" -exec somecommand '{}' \;

The above command will search in $LOCATION for all files named $FILENAME and apply the command that you define at somecommand.

The argument ‘{}’ inserts each file found into the somecommand syntax. The \; argument indicates the exec command line has ended — YOU MUST INCLUDE IT.


Find all files that contain a string (Get filenames) 5

Assuming you have a lot of files and you need to find all files that contain a certain string value, you can check them all automatically using the following command.

Method 1 – Using find -exec

Using the exec flag of find, you can process all files even those that their filenames contain single or double quotes or other special characters.
The following command will return a list, the list of files that contain the value ‘string’.

find . -type f -exec grep 'string' -s -l '{}' \;

The above command breaks down as follows:

  • find . -type f Find all files in current directory.
  • -exec For each match execute the following.
  • grep 'string' '{}' Search the matched file '{}' if it contains the value ‘string’.
  • -s Suppress error messages about nonexistent or unreadable files.
  • -l (lambda lower case) or --files-with-matches Suppress normal output, instead print the name of each input file from which output would normally have been printed. The scanning will stop on the first match.

To exclude binary files from matching, add the -I parameter on grep.

Method 2 – Using xargs

This method will not work for filenames that contain single quotes as it will confuse xargs.

find . -type f | xargs grep 'string' -s -l;

To exclude binary files from matching, add the -I parameter on grep.

Note: WordPress might change/replace the apostrophe to another ASCII apostrophe punctuation symbol! Make sure you use the straight apostrophe symbol or else you will not get the result expected since the behavior of grep will change. See Apostrophe on WikiPedia Here.