grep


Bash: grep: A couple of usefull applications

(How) to delete all empty lines from a file:

cat someFile | grep -v '^$'

(How) to get all numbers that have no sign in front of them (all positive numbers, from a file where on each line there is one number only):

cat someFile | grep ^[0-9]

(How) to extract all negative numbers (from a file where on each line there is one number only):
You can of course replace the minus ‘-‘ character with any other you want to use as a starting character for a line.

cat someFile | grep ^-


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.