A Quick and Dirty grep tutorial



Basic syntax:
grep 'search pattern' filename

NOTE: best to use single quotes

example
    grep 'bill' names.txt     <------find all lines containing bill in file names.txt

    grep -n 'bill' names.txt <--------same as above, but also include line numbers

    grep -i 'bill' names.txt  <---------ignore case. Will find bill BILL BiLl biLL etc

    grep -v 'bill' names.txt <-------- invert. Will print out every line that does not contain bill

Anchors:

    grep -n '^bill' names.txt <--------find all lines that **begin** with bill

    grep -n 'bill$' names.txt <--------find all lines that end in bill

Character classes

    grep -n '[bB]ill' names.txt <----------find all lines that contain bill or Bill

    grep -n '[0123456789]' names.txt <-------find all lines that contain a digit

    grep -n '[0-9]' names.txt <------same as above

    grep -n '[0-9][0-9]' names.txt <--------find all lines that contain at least 2 consecutive digits

    NOTE: a carat (^) inside a character class negates all elements of the chararcter class. For example
    [0-9] matches any digit and [^0-9] matches anything except a digit

    grep -n "^[^0-9]" names.txt <----- finds all lines that do not begin with a digit.


Remember - you can pipe output to grep, as in

    last |grep "^smith"            <------this will output all sign-ons to the system for user smith

Repeat specifiers

.  matches any single character
+ matches the preceding character 1 or more times
* matches the preceding character 0 or more times


grep 'b.t" sample.txt    matches bat,bbt,bct,b5t,
grep '[0-9]+' sample.txt   matches  5,56,567,1234,