1833776 Members
2056 Online
110063 Solutions
New Discussion

Help with Grep

 
SOLVED
Go to solution
Ted Flanders
Frequent Advisor

Help with Grep

Here is the problem.

I am doing a grep on a file. I only want lines where the search string is matched exactly.

command % grep exam filename

filename contents:
line 1)here:is:my:exam:contents
line 2)here:is:yourproblem:example

The problem is that grep will return both lines because it matches all or part of the search string. Lines that conatina both "exam" and "example" are returned. I only want line 1 to be returned, an exact match. I have looked thru the man pages and I don't see any options that will work. I know it can be done. I am also looking into awk. Any ideas????

7 REPLIES 7
Patrick Wallek
Honored Contributor

Re: Help with Grep

If the word you are looking for is surrounded by a space, or any other character (: ; etc..) then you can do a: grep " exam " filename

Patrick Wallek
Honored Contributor

Re: Help with Grep

I realized after I hut submit that I probably didn't explain that well. In the grep command put the exact string you are looking for, like " exam " where exam is surrounded by a space, or ":exam:" where exam has a : on either side of it. That should work for you.
Tony Vilardi
Advisor

Re: Help with Grep

There is an option to grep that will give you only the exact match of the string you enter.

Check the man page for grep.
The -x option returns only exact matches.

Tony
Rick Garland
Honored Contributor

Re: Help with Grep

Check out the -x option to grep. This option is for exact matches
Ted Flanders
Frequent Advisor

Re: Help with Grep

I will assign points as soon as it lets me....thanks!!!
Rodney Hills
Honored Contributor
Solution

Re: Help with Grep

I think awk might be better for you.

awk -F: '$3="exam"{print $0}'
It is more cryptic looking, but if you are planning on doing look ups in a script and need exact matches on a field within a file, then awk gives you more control.

By the way, the -x option of grep looks for exact matches across the entire line.

If you are planning on doing some really tricky stuff with the file, then "perl" has much better text file processing.
There be dragons...
Dan Hetzel
Honored Contributor

Re: Help with Grep

Hi Ted,

You'll have to use grep with a character class like in:

grep -E "[^[:alpha:]]exam[^[:alpha:]]"

This will match the string "exam" providing it is surrounded by non alpha characters.

If you want to match your string in cases where it is either starting or ending the line, then the expression becomes:

grep -E "[^[:alpha:]]exam[^[:alpha:]]|^exam[^[:alpha:]]|[^[:alpha:]]exam$"

Becomes to be unreadable, doesn't it ?

;-)

See man regexp for definitions of character classes.

Best regards,

Dan
Everybody knows at least one thing worth sharing -- mailto:dan.hetzel@wildcroft.com