Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

simple bash question

Status
Not open for further replies.

fugtruck

MIS
Jul 1, 2009
62
0
0
US
I want to search a text file for the existence of certain strings and execute a command if they exist, something along the lines of:

if <string> exists
command

or

if <any member of this list exists>
command

Any suggestions? I know how to manually search a file with grep, cat, etc., but the "if this exists" part eludes me.
 
I'm no bash expert, but I think this'll do.
Code:
#!/bin/bash
COUNT=`grep -c "php" test.php`
if [ $COUNT != 0 ]
then
echo "do something"
else
echo "do something else"
fi

-----------------------------------------
I cannot be bought. Find leasing information at
 
guess im a little fuzzy on your requirements but if you just want to see if a file contains a string and do something if it does then simply:
Code:
grep <string> <file> && <command>
 
Consider also using the grep -q option if you want to do it silently, or if that option is not available on your OS, redirect the output to /dev/null. Another syntax more appropriate for multiple commands would be:

Code:
if grep -q <string> <file>
then
    echo "do something"
else
    echo "do something else"
fi

Annihilannic.
 
Hi

Regarding the second part of your "or", in case this was also part of the question :
fugtruck said:
if <any member of this list exists>
See if your [tt]grep[/tt] implementation supports the -f option :
man grep said:
[tt] -f FILE, --file=FILE
Obtain patterns from FILE, one per line. The empty file
contains zero patterns, and therefore matches nothing. (-f is
specified by POSIX.)[/tt]
Code:
grep -qf <file-with-strings> <file-to-search> && <command>

[gray]# or[/gray]

echo <list-of-strings> | grep -qf - <file-to-search> && <command>
Tested with GNU [tt]grep[/tt].

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top