Linux utilities: GREP
Introduction to GREP
grep, egrep, fgrep – prints line matching pattern (regular expression)
Features:
1. The ability to parse lines based on text and/or RegExes
2. Post-processor
3. Searches case-sensitively, by default
4. Searches for the text anywhere on the line
Examples:
1. grep ‘Linux’ grep1.txt – normal search – searches Linux in grep1.txt and not linux
2. grep -i ‘linux’ grep1.txt – case-insensitive search search
3. grep ‘^linux’ grep1.txt – uses ‘^’ to anchor searches at the beginning of lines
4. grep -i ‘linux$’ grep1.txt – uses ‘$’ to anchor searches at the end of lines
Note: Anchors are RegEx characters (meta-characters). They’re used to match at the beginning and end of lines
5. grep -a ‘myfuncion’ binfile – searches binary file as if it is a text file
6. grep ‘[0-9]’ grep1.txt – returns lines containing at least 1 number
7. grep ‘[a-z]’ grep1.txt – returns lines containing at least 1 alphabet
8. rpm -qa | grep grep – searches the package database for programs named ‘grep’
9. rpm -qa | grep -i xorg wc -l – returns the number of pacakges with ‘xorg’ in their names
10. grep -c ‘name’ myfile1 myfile2 – returns the count of matching lines in each file
11. grep -v sshd messages – performs and inverted search (all but ‘sshd’ entries will be returned)
13. grep -C 2 sshd messages – returns 2 lines, above and below matching line
14 grep -o ‘matchtext’ myfile – returns only the matching part and not the complete line.
Note: Most, if not all, Linux programs log linearly, which means one line after another, from the earliest to the current
Note: Use single or double quotes to specify RegExes
Also, execute ‘grep’ using ‘egrep’ when RegExes are being used