1752782 Members
6341 Online
108789 Solutions
New Discussion юеВ

Re: Grep on fixed value

 
SOLVED
Go to solution
dev44
Regular Advisor

Grep on fixed value

Hi,

I have a file like this:

hello
hello123
hello345
hello678

I want to grep on "hello" and only output the first line. So I want to grep for "hello" as a fixed or absolute value.
whatever
5 REPLIES 5
James R. Ferguson
Acclaimed Contributor
Solution

Re: Grep on fixed value

Hi:

Anchor the pattern:

# grep ^hello$ file

Regards!

...JRF...
dev44
Regular Advisor

Re: Grep on fixed value

It came back with no ouput at all.
whatever
James R. Ferguson
Acclaimed Contributor

Re: Grep on fixed value

Hi:

> It came back with no output at all.

Then there is probably whitespace before and/or after the "hello" token. This is easy to fix:

# perl -ne 'm{^\s*hello\s*$} and print' file

The '\s' denotes whitespace (spaces, tabs). The anchors (^ and $) make sure that the spaces are the ONLY characters preceding or trailing the token to match.

Regards!

...JRF...
TTr
Honored Contributor

Re: Grep on fixed value

After 11.11 the grep command has the -w option which greps for whole word only and will work if the work hello had leading and trailing spaces as well.
grep -w hello hello-file
Dennis Handly
Acclaimed Contributor

Re: Grep on fixed value

>JFR: Anchor the pattern: grep ^hello$ file

Instead of doing that you could use -x.
Since you don't have a pattern you can just use fgrep -x. Except as JRF said, you seem to have trailing spaces, so you can use grep -w as TTr mentioned.