Searching for a specific string in a file

Hi

I am trying to search for a certain set of patterns within a file, and then perform other commands based on output.

testfile contents:

password    requisite     pam_cracklib.so lcredit=-1 ucredit=-1 ocredit=-1

script:

D="dcredit=-1"

if [ "cat testfile | grep -w "$D"" ]
then
echo $D exists
else
echo $D doesnt exist
fi

Tried executing, but it always outputs true regardless of whether $D is present or not.

Can someone please assist?

Thank you

Try something like this:

if grep -q "$D" testfile 
then
   echo "there"
else
   echo "not there"
fi

You don't need to cat to grep; grep will read the file. You also don't want to test the output string like that. Test the return code from grep which will be 'success' if the pattern was matched.

1 Like

Try:

if grep -wq "$D" testfile
then
echo $D exists
else
echo $D doesnt exist
fi
1 Like

Thank you for clearing this.

I tried with this

[ "`cat testfile | grep -w "$D"`" ]

and it worked too.

I am also trying at a later stage to get multiple grep conditions checked. Such as ,

if  grep -qw '"$D"|"$L"' testfile

Dont think im doing it right here. Does this need to be enclosed in [ ] ?

Thanks very much

You'll need to change things a wee bit.

First, I think, you'll need egrep if you are going to use 'pattern|pattern'. At least my version of grep won't do this, but egrep will.

Second, your variables won't expand inside of single quotes. Put both patterns into one set of double quotes.

Finally, you shouldn't put the command inside of brackets. Something like this should work:

if egrep -qw "$D|$L" testfile
then
    execute some command
fi
1 Like

It is hard to guess what you intended from faulty code. Please describe the condition in words.
Things to bear in mind.
Variables enclosed by single quote characters are not expanded.
The "grep" command does not recognise "|" as meaning "or". The "egrep" command does.
A command sequence in an "if" statement does not execute automatically. It needs either backticks or $( ) command syntax.

Beg to differ, but at least in Kshell and bash a command executes without $(..) or `..` when placed on an if.

spot: ls >/tmp/x
spot: if grep -q foo /tmp/x
> then
> echo true
> fi
true

Oh sorry, I thought it was clear from my 1st post that I was trying to search for multiple strings (of which one was defined ..$D)!!

Dint know this one, Thank you!

Can you explain why this is so?

"if" waits a command, and "[" is just a command. Really this is a synonym for "test". When command executes it returns exit code. If exit code == 0 then "if" counts it as true condition and executes commands in its body.

When you write, for example

if [ -f 'some_file' ]; then ...

really you run the command:

if test -f 'some_file' ; then ...

In case of grep - this command returns 0 if it finds matches or non-0 if it's not. This is perfect condition for "if".

Excuse me if something is unclear. I'm working on my English.