1748235 Members
3403 Online
108759 Solutions
New Discussion юеВ

Re: grep command

 
SOLVED
Go to solution
Tarek
Super Advisor

grep command

I work on hp systems. I want to find some entries in the /etc/hosts. I wrote a script, but while i issue the grep command i have some problems.
For example if i make grep hp1 /etc/hosts i will see all ws that begins with hp1 so also hp12, hp110, hp19 and so on..
I want to find only hp1. I know that with sun the command is grep -w, but this doesn't exist on hp, what is it's correspondance? I looked in the grep's man, but i didn't find it. (maybe i didn't look well!!)
13 REPLIES 13
Laurent Paumier
Trusted Contributor
Solution

Re: grep command

You could replace the grep command with perl. Perl has a smarter regexp syntax :

# perl -ne '/\bhp1\b/ && print' /etc/hosts

(\b stands for word boundary)
Alexander M. Ermes
Honored Contributor

Re: grep command

Hi there.
Try this :

grep 'hp1 ' /etc/hosts

Rgds
Alexander M. Ermes
.. and all these memories are going to vanish like tears in the rain! final words from Rutger Hauer in "Blade Runner"
Tarek
Super Advisor

Re: grep command

Thanks to both!! But i have still a problem. How can i implement your code in the script.
#!/sbin/sh
echo > /tmp/list
for i in 'cat /tmp/hplist'
do
grep $i /etc/hosts >> /tmp/list
done
I saw that if i put $i between '$i ', the output is wrong.
federico_3
Honored Contributor

Re: grep command

I'd do like the following :

grep hp1$ /etc/hosts
federico_3
Honored Contributor

Re: grep command

#!/sbin/sh
echo > /tmp/list
for i in 'cat /tmp/hplist'
do
grep $i$ /etc/hosts >> /tmp/list
done
Thierry Poels_1
Honored Contributor

Re: grep command

hi,
grep "$i " ...
instead of
grep '$i ' ...
With single quotes your variable will not be translated, and grep will search for $i (dollar-i) in your file.
regards,
Thierry.
All unix flavours are exactly the same . . . . . . . . . . for end users anyway.
Tarek
Super Advisor

Re: grep command

The "$i " and $i$ works so and so. The problem is that they don't search every entry that i have in the list in /etc/hosts.
So the script isn't helpful.
Robin Wakefield
Honored Contributor

Re: grep command

grep -e "$i[ ]" -e $i$ /etc/hosts

where you type space followed by tab in the square brackets.

If this doesn't work, what type of expression is not being captured?

Robin.
Robin Wakefield
Honored Contributor

Re: grep command

...or try this too:

grep -E "$i( | |$)" /etc/hosts

again, it's space,pipe,tab,pipe,dollar in the brackets.

Robin.