Grep & RegExp Flashcards
Learn all about grep command and regular expressions
To find lines in test.txt that have word “seven”
So if you have lines
line 1: five seventeen two
line 2: five seven two
only “five seven two “ will be found
grep -w ‘seven’ test.txt
To find lines in test.txt where we have words that start with “seven”
grep ‘\
To find in file test.txt lines where we have words that ends with seven, like ‘seven’ not ‘seventeen’
grep ‘seven>’ test.txt
To find in test.txt file lines which start with seven. So
will be found: ‘seven five two’
but
won’t be found: ‘five seven two’
grep ‘^seven’ test.txt
To find in test.txt file lines which end with seven. So
five two seven - will be found
but
five seven two - won’t be found
grep ‘seven$’ test.txt
For file test.txt
- To show one line before and one row after the grep pattern in the file test.txt like
#line UP
twentyseven
#line down - To show one row before grep pattern
#line UP
twentyseven - To show one row after grep pattern
twentyseven
#line down
- before and after: grep -C 1 twentyseven test.txt
- after match: grep -B 1 twentyseven test.txt
- before match: grep -A 1 twentyseven test.txt
To show lines where twenty1, twenty2, twenty3, twenty4 exist
for
twenty1
twenty3
twenty5
twenty7
grep “twenty[1-4]” test.txt
To exclude lines where twenty1, twenty2, twenty3, twenty4 exist
for
twenty1
twenty3
twenty5
twenty7
grep “twenty[^1-4]” test.txt
nameserver 127.0.0.1
For file test.txt
nameserver 8.8.8.8
nameserver 77.88.8.8
nameserver 8.8.4.4
show lines with ip and exlude lines which are comments - have # at the begining
grep -E ‘\b[0-9]{1,3}(.[0-9]{1,3}){3}\b’ /etc/resolv.conf | grep -v ‘#’
will show
nameserver 8.8.8.8
nameserver 77.88.8.8
nameserver 8.8.4.4
and wont show #nameserver 127.0.0.1
For file test.txt #nameserver 127.0.0.1 nameserver 8.8.8.8 nameserver 77.88.8.8 nameserver 8.8.4.4
to show only ip excluding line with a comment (line starts with #) Will be shown 8.8.8.8 77.88.8.8 8.8.4.4
not
127.0.0.1
grep -v ‘#’ /etc/resolv.conf | grep ‘\b[0-9]{1,3}(.[0-9]{1,3}){3}\b’
Case insensitive search of grep_pattern using grep in file test.txt
grep -i grep_pattern file_pattern test.txt
A regular expression matches any single character
the sign “.”
e. g.
text. *text
text. text
Specify the color parameter in a grep-specific environment variable
$ export GREP_OPTIONS=’–color=auto’ GREP_COLOR=’100;8’
Searching in all files recursively using grep. When you want to search in all the files under the current directory and its sub directory
grep -r “ramesh” *
Invert match using grep (exclude pattern from the search)
grep -v “go” demo_text