Operating System - Linux
1756750 Members
3173 Online
108852 Solutions
New Discussion юеВ

grep - searching exact pattern

 
Dennis Handly
Acclaimed Contributor

Re: grep - searching exact pattern

>my requirement is to search pattern "exit"(exactly the same, should not be "#exit") in a file.

Mine would select #exit since I'm only looking for "words". You can always pipe my output into grep -v and remove "#exit" and all other false positives until you get closer to what you want.

grep -w also finds "#exit".
Matti_Kurkela
Honored Contributor

Re: grep - searching exact pattern

The "grep" command uses regular expressions. Unless you specifically say otherwise, regular expressions always assume that there may be any amount of text before or after the pattern. All tools that use regular expressions behave like this.

grep 'exit' /some/file

looks for the four letter string "exit" and displays all the lines where it appears anywhere on the line. In effect, it's the same as:
grep '.*exit.*' /some/file

If you want to restrict the matching to something that is on the beginning of line, you must anchor the beginning of the match, like this:

grep '^exit' /some/file

'^' means "beginning of line".

If you want to match something at the end of line, there is a different anchor for that:

grep 'exit$' /some/file

If you want to match when your pattern covers the entire line (i.e. the matching text is the only thing on the line), use both anchors together:

grep '^exit$' /some/file

This searches for lines that have *only* the word "exit" and nothing else.

Note that I'm using single quotes around the pattern: this way there will be no problems with special characters like "$".

If you need to use environment variables within your pattern string, you should use double quotes instead. Then you may need to replace the end-of-line anchor "$" with "\$" so the shell does not think you're specifying a variable name.
MK
Dennis Handly
Acclaimed Contributor

Re: grep - searching exact pattern

>Matti: Then you may need to replace the end-of-line anchor "$" with "\$" so the shell does not think you're specifying a variable name.

Note: This isn't needed if you are using a real shell. This is only needed if you are using the scummy C shell.
Rasheed Tamton
Honored Contributor

Re: grep - searching exact pattern

Hi Anil,

Try this

grep -F -x exit filename

will exactly match the string "exit" from the filename.

Regards,
Rasheed Tamton.
Rasheed Tamton
Honored Contributor

Re: grep - searching exact pattern

Oops!!

I did not test with the multiword lines. It is only applicable to single word lines as already mentioned.

Regards,
Rasheed Tamton.