Tuesday, April 5, 2011

How to search an expression in a file from a bash script?

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

Thanks in advance

From stackoverflow
  • grep is your friend here

  • 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
    
    Paul Creasey : I prefer `if [ $(grep -c "text" file) -gt 0 ]` but it the same thing.
    Gordon Davisson : 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.
  • cat <file> | grep <"text"> and check the return code with test $?

    Check out the excellent: Advanced Bash-Scripting Guide

  • 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
    
  • 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
    
  • just use the shell

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

0 comments:

Post a Comment