Linux Command - grep
grep
command, which stands for “global regular expression print,” processes text line by line
and prints any lines which match a specified pattern.
To print only the matched part, use -o
option
Options
command options
option | description |
---|---|
-e PATTERN | use PATTERN as the pattern. This can be used to specify multiple search patterns |
-E, –Extended-regexp | Interpret PATTERN as an extended regular expression |
-i, --ignore-case | ignore case in both the PATTERN and input files |
-H | print filename |
-n, --line-number | prefix each line of ouput with 1-based line number |
-R, -r, --recursive | read all files recursively |
-v | invert the matching |
-o, –only-matching | -o print only the matched (non-Empty) parts of a matching line |
for context control
- -A NUM –> print NUM lines of trailing output context
- -B NUM –> print NUM lines of leading output context
- -C NUM –> print NUM lines of output context
Example
find “foo” in file and prints lines that contains “foo”. Note that “foo”, “food” and “ofoo” are all matches.
1 | grep -i "foo" file1 |
find “foo” in files and prefix lines with filename and line number
1 | grep -inH "foo" words.txt |
sample output:
1 | words.txt:1:food |
find exact match
The line matches exactly “foo”
1 | grep "^foo$" |
Search the words that starts with ‘con’
search for words that start with con
. examples are ‘contribution’, ‘control’. Only output the matched part
1 | cat LICENSE-2.0.txts | grep -o "con\w*" |
here \w*
is used to match any number of characters
Search the words that starts with ‘con’, then 3 characgers and ends with t. Here we need to use -E option to use extended regex.
1 | cat LICENSE-2.0.txt | grep -o -E "con\w{3}t" |
sample outputs are content
and consist
Search directory recursively
1 | grep -inr "foo" dir |
Output with context
1 | grep -in -C 3 "foo" filename |
Search multiple patterns
1 | grep -in -E firefox -E chromium filename |
Search pattern starts with hyphen(-)
Need to use -E option for searching String “-notify”
1 | grep -in -E -notify filename |
ls directories in current directory
use regular expression to match the directories
1 | ls -l | grep "^d" |
Similarly, to list regular files
1 | ls -l | grep "^-" |
ls non-directories in current directory
use -v
to invert the results.
1 | ls -l | grep -v "^d" |
ls directories that ends with ‘k’
use regular expression to match the directories the ends with ‘k’
1 | ls -l | grep "^d.*k$" |