Linux – grep command hacks

grep

grep command print lines matching a pattern. grep is a powerful command for file searching text.

here the real-time use full command hacks.

The example is the sample file and data.

# cat > testfile
one
two
three
four
five
six
seven
eight
nine
ten
  • Search string in a file
Syntax: grep 'string' filename
Example: 
# grep 'three' testfile 
three
  • Search a string in multiple files
Syntax: grep 'string' *
# grep 'eight' *
eight
  • Display the line before/after of match string
Syntax: grep -A <no of lines> -B <no of lines> 'pattern' filename

# grep -A 2 -B 2 'five' testfile
three
four
five
six
seven
  • Counting the matching the words in a file
Syntax: grep -c 'pattern' filename

# grep -c 'six' testfile 
1
  • Find the files while matches the string
Syntax: grep -w 'string' filename

# grep -w 'six' testfile 
six
  • Display line number which matches the string
Syntax: grep -n 'string' filename

# grep -n 'six' testfile 
6:six
  • Case insensitive search in a file
Syntax: grep -i 'string' filename

# grep -i 'SIX' testfile 
six
  • Display the only file name which matches the pattern
Syntax: grep -l 'pattern' filename

# grep -l 'six' testfile 
testfile
  • Display only matched the pattern
Syntax: grep -o 'pattern' filename

# grep -o 'thr' testfile 
thr
  • Search the lines which match the start of the word
Syntax: grep - '^word' filename

#grep '^e' testfile 
eight
  • Search the lines which match the end of the word
Syntax:grep 'word$' filename 

# grep 'e$' testfile 
one
three
five
nine
  • Search the string by specifying the regex pattern
Syntax: grep 'regex' filename

# grep [wn] testfile 
one
two
seven
nine
ten
  • Highlighting the matched search with color
Syntax: grep --color=options 'pattern' filename

There are 3 color options available to you:
--color=auto
--color=always 
--color=never

# grep --color=always [wn] testfile 
one
two
seven
nine
ten
  • Search the pattern recursively
Syntax: grep -r 'pattern' foldername

# grep -r [wn] . 
./testfile:one
./testfile:two
./testfile:seven
./testfile:nine
./testfile:ten
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s