Unix - Examples for grep command

Unix - Examples for grep command

 
Below are some examples on the usage of grep and egrep in Unix.
We are using file text.txt as our source file.

Content of text.txt
==================================================================
one
two
three
four
five
six
seven
eight
nine

==================================================================

To print NUM lines of trailing context after matching lines.
==================================================================
[root@server:~] $grep -A<NUM of lines> <pattern> <file>
[root@server:~] $grep -A2 six text.txt
six
seven
eight

==================================================================

To print NUM lines of leading context before matching lines.
==================================================================
[root@server:~] $grep -B<NUM of lines> <pattern> <file>
[root@server:~] $grep -B2 six text.txt
four
five
six

==================================================================

To print all except lines matching pattern.
==================================================================
[root@server:~] $grep -v <pattern> <file>
[root@server:~] $grep -v six text.txt
one
two
three
four
five
seven
eight
nine

==================================================================

Using egrep to print lines matching either pattern.
==================================================================
[root@server:~] $grep -v '<pattern1>|<pattern2>' <file>
[root@server:~] $egrep 'six|seven' text.txt
six
seven

==================================================================
0 (0)
Article Rating (No Votes)
Rate this article
Attachments
There are no attachments for this article.
Comments
There are no comments for this article. Be the first to post a comment.
Full Name
Email Address
Security Code Security Code
Related Articles RSS Feed
Transform XML to CSV Format | Unix String Pattern Manipulation The Ugly Way
Viewed 8568 times since Sun, Jan 9, 2022
bash for do done AIX
Viewed 2773 times since Mon, Jun 4, 2018
Convert CSV to JSON with bash script
Viewed 6301 times since Mon, Jan 20, 2020
java Simple Java JDBC Program To Execute SQL Update Statement
Viewed 16841 times since Sun, Jan 9, 2022
To do a quick check on the number of path present (does not mean all are Enabled] using for loop
Viewed 5322 times since Fri, Jun 8, 2018
Display basic information about Physical Volumes
Viewed 4591 times since Sun, Jun 3, 2018
Unix - eval command example
Viewed 2811 times since Fri, Jun 8, 2018
Convert JSON to CSV with bash script
Viewed 14574 times since Mon, Jan 20, 2020
Epoch & Unix Timestamp Conversion Tools
Viewed 87547 times since Fri, Jun 22, 2018
java Simple Java JDBC Program To Execute SQL Select Query
Viewed 11591 times since Sun, Jan 9, 2022