Monday, March 16, 2020

20 grep, egrep and fgrep command examples in UNIX/Linux



1) How to find all matching lines in a file in UNIX?

$ grep "good" dict.txt

2) How to exclude lines in a file, which matches patterns using the GREP command?

$ grep -v

2) How to count the number of matching lines in a file in Linux?

$ grep -c "good" dict.txt

3) How to perform case insensitive search for a keyword in a text file?

grep command support case insensitive search through grep -i option, where i stands for ignore case. This is quite useful if you are looking for strings like "error", "Error" and "ERROR" in a file. without case insensitive search you may not get the full picture if your developers are using different cases for the same keyword. Doing a case the insensitive search will give you the full idea.

4) How to display matched keywords as colored in grep output?

5) How to perform a recursive search using grep command in UNIX?

By using grep -R option, which performs a recursive search to sub-directories

6) How to make your grep command faster?

 grep is very slow on UTF-8. Use “LANG=C grep …” to increase speed.

$ echo $LANG

en_US.UTF-8

$ time grep ‘^….’ /usr/share/dict/words >/dev/null

real 2m16.795s

user 2m10.536s

sys 0m0.087s

$ export LANG=C

$ time grep ‘^….’ /usr/share/dict/words >/dev/null

real 0m0.031s

user 0m0.028s

sys 0m0.003s

6) How to display lines above and below matching lines using grep command in Linux

grep support an option called --context

You have even option to display n number of lines after the match, or just show lines above and below of matching lines using -A and -B.

7)

How to learn more about grep command in Linux box itself, use the following commands :

man grep

info grep

8) How to search for a given string in multiple files in UNIX

how to print the name of all files which contains a particular String

9) How to use regular expression with grep command in UNIX.

You can use a basic set of regular expressions with grep command as shown below. There are two ways to use regular expression with grep command either by using grep -e option or grep --regex option

10) How to search for full words in a file in Linux using GREP

grep -w

11) How to display only the name of the files, which matches a given pattern?

Here we don't want matching lines to be printed, we only want to know the files, which contains matching lines.

grep -l option is our solution

12) How to show only the matched String

13) How to show the position of the match in the line

14) How to show numbers while display grep output

15) egrep command examples

16) fgrep command examples

That's all on this list of grep command examples in UNIX/Linux. We have learned a lot of good options of grep command, in fact, I would say Every Linux user must know these grep option to take full advantage of grep command in Linux. Let us know if you got any cool grep tips.