Follow this Blog!

Dec 21, 2012

f Comment

Unix: How Do I Print Files that Do NOT Contain the Given Query Pattern?

Amazon In Unix or Linux the grep command is not the easiest command to use. What's worse by default it prints every match between the query string and each line of the input file. Thankfully grep has a list of useful options that can help us do what we need to do as long as we know what those options or flags are.

If you'd like to get matches by comparing the query pattern (usually a plain string) to the entire input file instead of to each line of the entire input file, use -L or -l.

Below is what each option does in human understandable language instead of the roundabout language you see in 'man' definition:

-L, --files-without-match
Suppress normal output; instead print the name of each input file which contains NO matches at all.

-l, --files-with-matches
Suppress normal output; instead print the name of each input file which contains at least one match.

An Example
Suppose you have a list of HTML files on your web server and some of them have H1 tag and others don't, and you'd like to locate those that do NOT contain H1 tag so that you can add H1 tag to each of those HTML files. This command does that:

grep -L '<h1>' *
If you want the same operation done recursively then here's the command:

grep -R -L '<h1>' *
Easy when you understand how 'grep' Unix command works right?

If you have any questions let me know and I will do my best to help you!
Please leave a comment here!
One Minute Information - by Michael Wen
Find Michael on Google or Facebook
ADVERTISING WITH US - Direct your advertising requests to Michael