Searching patterns using grep command in Linux
grep command is used to search the pattern in input file or input string. Regular expressions are used to specify the pattern.
Here is the syntax of grep command.
grep <pattern> <filename>
To highlight the matches, you can set GREP_OPTIONS variable with below values.
We can use below command to find the pattern “abc” in file f1.txt
grep “abc” f1.txt
To make the search case insensitive, you can use -i switch
grep -i “abc” f1.txt
To print the line number where match is found, you can use -n switch
grep -n “abc” f1.txt
To print matched line and 3 lines after it, you can use below command
grep -n -A 3 “abc” f1.txt
To search for the pattern in all files in current directory and all subdirectories, you can use below command.
grep -r “abc” *
To suppress the message saying directories can not be searched, you can use -s switch.
grep -r -s “abc” *
We can use below command to find all lines not matching the pattern “abc” in file f1.txt. Here -v stands for inverted search.
grep -v “abc” f1.txt
Some more options on grep are given below.
- grep -w “abc” f1 : “-w” option can be used to search for words (not sub strings).
- grep -A 2 “abc” f1 : “-A” option can be used to display n lines after match.
- grep -B 2 “abc” f1 : “-B” option can be used to display n lines before match.
- grep -C 2 “abc” f1 : “-C” option can be used to display n lines before and after match.
- grep -e “term1” -e “term2” : “-e” option is used to search multiple patterns in a file.
- grep -c “abc” f1 : “-c” option is used to print the matches count.
- grep -l “abc” * : “-l” option shows files names that match the pattern. (Instead of matching lines)
- grep -o “xyz.*” f1 : “-o” option is used to print only the matched pattern (instead of whole line)
- grep -n “term” f1 : “-n” option is used to display matching line numbers
If grep command encounters any directory while trying to search a pattern, it gives warning message saying “xyz is a directory”. If you want to suppress this message, you can use “-s” switch.
egrep command is equivalent to “grep -E”. This is also called as extended grep.
fgrep command is equivalent to “grep -F”. This is also called as fast grep.