links: |- back -|- index -|- home -| end
grep is a powerful tool to search for strings or PATTERNS in a text file.
The simple usage is
~$ grep name file.txt
will find, and output all lines containing the letters 'name'. As usual $ grep --help will show the MANY options, and grep also uses 'regular expressions', like.
~$ grep run[- ]time *.txt
to find 'run time' or 'run-time' in all txt files. A table of 'regular expressions' -
^ (Caret) | = | match expression at the start of a line, as in ^A. |
$ (Question) | = | match expression at the end of a line, as in A$. |
\ (Back Slash) | = | turn off the special meaning of the next character, as in \^. |
[ ] (Brackets) | = |
match any one of the enclosed characters, as in [aeiou]. Use Hyphen "-" for a range,
as in [0-9] .
|
[^ ] | = | match any one character except those enclosed in [ ], as in [^0-9]. |
. (Period) | = | match a single character of any value, except end of line. |
* (Asterisk) | = | match zero or more of the preceding character or expression. |
\{x,y\} | = | match x to y occurrences of the preceding. |
\{x\} | = | match exactly x occurrences of the preceding. |
\{x,\} | = | match x or more occurrences of the preceding. |
See http://www.robelle.com/smugbook/regexpr.html for some more examples... |
Here is an example to output the number at the beginning of a string -
~$ grep -o ^[0-9] string
It will show ONLY (-o or --only-matching) the number at the beginning of the string, if one...
Normally 'grep' includes binary files in the search, but -I (equivalent to --binary-files=without-match), like
~$ grep -rI 'shape contours' .
would find only 'text' files, in all subdirectories (-r), containing the phrase 'shape contours'...
To search for an entry like '%e', '%20.15E', etc, try -
~$ grep -r '%[0-9\.]*[Ee]' *
Note the -r is to be recursive into sub-directories, the \. escapes the special character '.', the asterisk, '*' matches zero or more of the preceding...
To search for a line like '#define BOOST_VERSION 103401' try
~$ grep define[^\w]BOOST_VERSION[^\w][0-9] boost/version.hpp
Note the [^\w] means any character NOT (^) an alpha-numeric (\w) character. The [0-9] says followed by a number.
And if you just want the 3rd item, the number, then try
~$ grep define[^\w]BOOST_VERSION[^\w][0-9] file | awk '{ print $3}'
And assuming say this yields '103401', then this can be split by
~$ MAJBV=`echo 103401 | cut -b1-1` - to give '1' ~$ MINBV=`echo 103401 | cut -b2-4` - to give '034' ~$ BLDBV=`echo 103401 | cut -b5-6` - to give '01'
Then to check for say version '1.37.0' or greater...
if [ "$MAJBV" -lt "2" ]; then echo "Version greater than 1.37.0 - OK" else if [ "$MAJBV" -lt "37" ]; then echo "Version LESS THAN 1.37 - NEED UPDATE!" else echo "Version greater than 1.37.0 - OK" fi fi