Grep Command Examples
Grep Command Examples
Grep Command Examples
Grep is the frequently used command in Unix (or Linux). Most of us use grep just for finding the
words in a file. The power of grep comes with using its options and regular expressions. You can
analyze large sets of log files with the help of grep command.
Grep stands for Global search for Regular Expressions and Print.
This saves a lot of time if you are executing the same command again and again.
!grep
This displays the last executed grep command and also prints the result set of the command on
the terminal.
This is the basic usage of grep command. It searches for the given string in the specified file.
grep "Error" logfile.txt
This searches for the string "Error" in the log file and prints all the lines that has the word
"Error".
The -i option enables to search for a string case insensitively in the give file. It matches the
words like "UNIX", "Unix", "unix".
grep -i "UNix" file.txt
Some times, if you are searching for an error in a log file; it is always good to know the lines
around the error lines to know the cause of the error.
grep -B 2 "Error" file.txt
This will prints the matched lines along with the two lines before the matched lines.
You can search for a string in all the files under the current directory and sub-directories with the
help -r option.
grep -r "string" *
You can display the lines that are not matched with the specified search sting pattern using the -v
option.
grep -v "string" file.txt
You can remove the blank lines using the grep command.
grep -v "^$" file.txt
We can find the number of lines that matches the given string/pattern
grep -c "sting" file.txt
We can just display the files that contains the given string/pattern.
grep -l "string" *
15. Display the file names that do not contain the pattern.
We can display the files which do not contain the matched string/pattern.
grep -L "string" *
By default, grep displays the entire line which has the matched string. We can make the grep to
display only the matched string by using the -o option.
grep -o "string" file.txt
We can make the grep command to display the position of the line which contains the matched
string in a file using the -n option
grep -n "string" file.txt
The -b option allows the grep command to display the character position of the matched string in
a file.
grep -o -b "string" file.txt
The ^ regular expression pattern specifies the start of a line. This can be used in grep to match
the lines which start with the given string or pattern.
grep "^start" file.txt
The $ regular expression pattern specifies the end of a line. This can be used in grep to match the
lines which end with the given string or pattern.
grep "end$" file.txt