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.
This post is also available in: Greek
This may not work if you have filenames like:
My brother’s 12″ records.txt
Use GNU Parallel instead. Watch the intro videos http://www.youtube.com/watch?v=OpaiGYxkSuQ
Updated the article with find . -exec grep ‘string’ -sl ‘{}’ \; to support, hopefully more filenames, even the ones with special characters.
To get all files that contain a specific string and also print the content of the lines where this string appears, you can use the following:
NEEDLE='string'; find . -exec grep $NEEDLE -sl '{}' \; -exec grep $NEEDLE -s '{}' \;
What you have to do is set the string you are searching for in the NEEDLE variable that will be reused for both exec commands.
Also, use -I with grep to eliminate matches in binary files, unless of course you’re looking for such matches as well!
Pingback: Using a CSV input file, find all documents that contain any of the items in a cell of a column – Bytefreaks.net