1838624 Members
2104 Online
110128 Solutions
New Discussion

Grep in a script

 
SOLVED
Go to solution

Grep in a script

Hi there,

The answer to this is probably very simple but it is Monday morning so I appologise for being a bit dopey.

I am writing a script to search the passwd file for duplicate names. So far I have this:

cut -d: -f5 /etc/passwd |while read a
do
if [ grep -c $a /etc/passwd >1 ]
then
echo $a
fi
done

All I get when running this is 'A test command parameter is not valid' in line 4 (the grep command)

I know it is probably a simple syntax problem like I said, I've not quite woken up this morning.

Thanks in advance,

Christian Briddon
7 REPLIES 7
Steven Sim Kok Leong
Honored Contributor

Re: Grep in a script

Hi,

Replace > with -gt and put the grep within grave accent and double quotes.

cut -d: -f5 /etc/passwd |while read a
do
if [ "`grep -c $a /etc/passwd`" -gt 1 ]
then
echo $a
fi
done

Hope this helps. Regards.

Steven Sim Kok Leong
Tom Geudens
Honored Contributor

Re: Grep in a script

Hi,
I think your if should be
if [ $(grep -c $a /etc/passwd) >1 ]

Hope this helps,
Tom Geudens
A life ? Cool ! Where can I download one of those from ?
Volker Borowski
Honored Contributor

Re: Grep in a script

KISS - keep it simple and stupid...


cut -d: -f5 /etc/passwd | uniq -d

Print only duplicate lines
Volker
Deepak Extross
Honored Contributor

Re: Grep in a script


Volker,
Last I knew, it was "short & sweet".
Your version gives it a nice twist, though!
:-)

Re: Grep in a script

Thanks everyone. I will assign points.
Volker Borowski
Honored Contributor

Re: Grep in a script

(N/A pls)

Deepak,
actually it is not "mine" (no enlisted copyright).
I never heard of short & sweet before, but it's nice also.
;)
Robin Wakefield
Honored Contributor
Solution

Re: Grep in a script

Hi Christian,

cut -d: -f5 /etc/passwd | sort | uniq -c | grep -v "^ 1 "

will show you how many of each duplicate.

Keeping with your original script, modify it to:

cut -d: -f5 /etc/passwd |while read a
do
if [ `grep -c "$a" /etc/passwd` -gt 1 ]
then
echo $a
fi
done

Note the $a is quoted in case it's empty.

Rgds, Robin.