tags:

views:

35

answers:

6

I have a bash script. I need to look if "text" exists in the file and do something if it exists.

Thanks in advance

A: 

grep is your friend here

ennuikiller
+2  A: 

Something like the following would do what you need.

grep -w "text" file > /dev/null

if [ $? -eq 0 ]; then
   #Do something
else
   #Do something else
fi
jackbot
I prefer `if [ $(grep -c "text" file) -gt 0 ]` but it the same thing.
Paul Creasey
Martin's approach (with `grep -q`) is both faster (doesn't search entire file, just up to the first match) and (IMHO) cleaner than either of these approaches.
Gordon Davisson
A: 

cat <file> | grep <"text"> and check the return code with test $?

Check out the excellent: Advanced Bash-Scripting Guide

Rickard von Essen
+4  A: 

If you need to execute a command on all files containing the text, you can combine grep with xargs. For example, this would remove all files containing "yourtext":

grep -l "yourtext" * | xargs rm

To search a single file, use if grep ...

if grep -q "yourtext" yourfile ; then
  # Found
fi
Martin
+1  A: 

You can put the grep inside the if statement, and you can use the -q flag to silence it.

if grep -q "text" file; then
    :
else
    :
fi
John Kugelman
A: 

just use the shell

while read -r line
do
  case "$line" in
   *text* ) 
        echo "do something here"
        ;;
   * )  echo "text not found"
  esac
done <"file"
ghostdog74