grep - global regular expression parser.
Searches input for a match to a pattern defined by a regular expression.
Processes 1 line at a time.
Expects text based data, lines terminated in new-line character
Input most commonly a file or list of files but can also be provided using
the pipe delimiter or input redirection.
Output is to standard out, so output redirection commonly used to preserve
found match.
Output consists of whole lines containing the matched string.
Some Options :
- -i, --ignore-case - ignore case.
This is a global action.
grep -i "\<dog\>" - will match Dog, dog, dOg, DOG, doG, etc.
To look for a word that is upper lower case, use regular expression :
grep "\<[Dd]og\>" - will match Dog or dog
- -f FILE, --file=FILE
Applies multiple regular expressions defined in specified file.
First true match outputs line. No duplicate lines.
Helpful if using a lot of wild-cards or searching for quotes.
- -e regex - state expression[s] on command line.
By default, grep takes a single expression.
Multiple -e's can be used to state multiple expressions.
Treated as OR condition, first true match outputs line. No duplicate lines.
- -v, --invert-match - NOT, output line if not true.
Usually requires anchors to get good results.
- -w, --word-regexp - match on whole word.
Saves users the trouble of using the word anchors, \< and \>
- -c, --count - Count matches.
Doesn't show match, but give count of lines which contain match (or with
-v, lines that don't match.)
- -l, --files-with-matches - lists files.
Doesn't show matched lines, just lists file with match in them.
Usually used on a list of files.
grep -l "50GB hard drives" $HOME/Mail/*
- -L, --files-without-match - List files that don't contain
the string described.
- -q (Posix), --quiet, --silent - Don't show output, but exit with
success (rc=0) as soon as a match is located.
- -s, --no-messages - suppress error messages but show any matches
found and set return code.
* -q may cause portability problems.
A safer way of coding is to redirect output and errors to /dev/null.
grep "regex" file > /dev/null # no output.
grep "regex" file 2> /dev/null # no errors.
grep "regex" file > /dev/null 2>&1 # no output or errors.
- -n, --line-number - print line number of line with match.
Define a function called ask with the following code :
local ask
read -p "Continue : " ask
if echo $ask | grep -e "^[Yy]\(es\)\?$" > /dev/null 2>&1
then
echo "It's a yes"
elif echo $ask | grep -e "^[Nn]o\?$" > /dev/null 2>&1
then
echo "It's a no"
else
echo "Make up your mind"
fi
|
Then try the following :
ask yes
ask no
ask maybe
ask Y
ask No