grep

 

grep

 


     

  1. Extract lines with phrase "Silver rocket"
    grep "Silver rocket" filename

     

  2. List names of files that contain the word "hummingbird"
    grep -l hummingbird *.csv > filelist.txt &

     

  3. Use grep as a filter
    ls -l | grep string

     

  4. Grep for word "unix", irrespective of case
    grep -i unix *.html

     

  5. Select all lines containing xyz followed by any 2 numbers
    grep 'xyz[0-9][0-9]' filename

     

  6. Retrieve all lines that begin with a space
    grep '^ ' filename

     

  7. Retrieve all lines that do not begin with a space
    grep '^[^ ]' filename

     

  8. Search directories recursively
    grep -r string /directory/name

     

  9. Search directories recursively, looking only in *PD files
    find /directory/name -name '*PD' -print | xargs grep string /dev/null

     

  10. Retrieve all lines that begin with a number
    grep '^[1-9]' filename

     

  11. Retrieve lines with string and the lines above and below string
    grep -C 2 'string' filename

     

  12. Retrieve lines containing string with a leading dash (-)
    grep -e '-string' filename

     

  13. Retrieve lines containing both string1 and string2
    /usr/xpg4/bin/grep -E 'string1|string2' tmp.out

     

  14. Have grep return a status code (0 or 1) for testing
         if grep -s $1 $2 
         then 
            echo "Found it"     
         else 
            echo "Did not find it"     
         fi
    

     

  15. Test if file exists and is readable:
         if test -r filename     
         then 
             grep $1 filename
         else 
             echo "ERROR!  Database file does not exist or is not readable".     
         fi