Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make grep only match if the entire line matches?

Tags:

grep

shell

unix

I have these:

$ cat a.tmp ABB.log ABB.log.122 ABB.log.123 

I wanted to find a exact match of ABB.log.

But when I did

$ grep -w ABB.log a.tmp ABB.log ABB.log.122 ABB.log.123 

it shows all of them.

Can I get what I wanted using grep?

like image 334
Johnyy Avatar asked Jan 17 '11 03:01

Johnyy


People also ask

How do you grep an entire line?

The grep command prints entire lines when it finds a match in a file. To print only those lines that completely match the search string, add the -x option. The output shows only the lines with the exact match.

How do you only grep an exact word?

The easiest of the two commands is to use grep's -w option. This will find only lines that contain your target word as a complete word. Run the command "grep -w hub" against your target file and you will only see lines that contain the word "hub" as a complete word.

How do you grep multiple lines after a match?

Use the -A argument to grep to specify how many lines beyond the match to output. And use -B n to grep lines before the match. And -C in grep to add lines both above and below the match!

How do you grep for lines that don't match?

To display only the lines that do not match a search pattern, use the -v ( or --invert-match ) option. The -w option tells grep to return only those lines where the specified string is a whole word (enclosed by non-word characters). By default, grep is case-sensitive.


2 Answers

grep -Fx ABB.log a.tmp 

From the grep man page:

-F, --fixed-strings
Interpret PATTERN as a (list of) fixed strings
-x, --line-regexp
Select only those matches that exactly match the whole line.

like image 134
John Kugelman Avatar answered Sep 22 '22 06:09

John Kugelman


Simply specify the regexp anchors.

grep '^ABB\.log$' a.tmp 
like image 42
user562374 Avatar answered Sep 20 '22 06:09

user562374