1847175 Members
5473 Online
110263 Solutions
New Discussion

Re: Grep question

 
SOLVED
Go to solution
Jeff Picton
Regular Advisor

Grep question

Hi

I know this may sound a bit basic but I would like to know how to use grep so that the outcome is true if and only if an EXACT match is found to a string.

Jeff
8 REPLIES 8
Pete Randall
Outstanding Contributor

Re: Grep question

Jeff,

As in

grep " Jeff Picton " somefile

?


Pete

Pete
Jeff Picton
Regular Advisor

Re: Grep question

Hi

Yes I am aware of that but when I do say grep "e" /etc/hosts, I get every entry in the host table containing e.

I don't know why
Pete Randall
Outstanding Contributor

Re: Grep question

Jeff,

That's the way grep functions. If you want to be more specific, you need to do so when you specify your string.


Pete

Pete
Ravi_8
Honored Contributor

Re: Grep question


Hi Jeff

since you are grepping for "e" in /etc/passwd, it is showing all the lines containing character "e"

man grep will explain you better.

if you don't lines without "e"

grep -v e /etc/passwd
never give up
Jeff Picton
Regular Advisor

Re: Grep question

Hi

OK that fine but what about if I want to produce an error message so that the outcome of grepping a typo error for example a single character returns false unless there is a machine who is labelled e in the host file ?
Jakes Louw
Trusted Contributor

Re: Grep question

Hi Jeff

grep "e" is perhaps a little simple for what you seem to require.

What is your actual requirement? A letter in a specific position in a line or word?

Here's a conditional check for the presence of a string in a file:

for i in $string
do
grep $i my_input_file
if [ $? -eq 0 ];then
echo $i " exists"
else
echo $i " does not exist"
fi
done

Trying is the first step to failure - Homer Simpson
Pete Randall
Outstanding Contributor
Solution

Re: Grep question

Jeff,

Then you need to use regular expression syntax. See man 5 regexp. Something like:

grep '^e$' /etc/passwd

might be what you're looking for.


Pete

Pete
Jean-Louis Phelix
Honored Contributor

Re: Grep question

Hi,

Beginning with 11.11 you also have the '-w' option to grep a word (beginning or end of a line, or separated with 'non word' char). Also the '-x' option allows you to grep an exact string, which mean a line only composed of that string.

Regards.
It works for me (© Bill McNAMARA ...)