Monday 6 April 2020

40 Examples of grep command in Linux

Searching and mining text inside a file with grep

man grep
grep "string" demo_file      #string search
grep "string" demo_file test_file.txt
grep "string" *.*

grep “^hello” file #match all lines start with ‘hello’
grep “done$” file #match all lines end with 'done'
grep “[^aeiou]” file #Match all lines not contain a vowel
grep -n "string" demo_file      # show line numbers with match

egrep is the same as grep -E
fgrep is the same as grep -F
rgrep is the same as grep -r
egrep IP /etc/hosts
egrep 'IP1|IP2' /etc/hosts

seq 10 | grep 5 -A 3        #print 5-8
seq 10 | grep 5 -B 3        #print 2-5
seq 10 | grep 5 -C 3        #print 2-8
echo -e "a\nb\nc\na\nb\nc" | grep a -A 1

grep word filename --color=auto #add color
grep --color "string" demo_file
grep --color -n "string" demo_file
yum search php | grep gd
grep -E "[a-z]+" demo_file #extented
grep "[a-z]+" demo_file

grep -v "string" demo_file     #inverted result
grep -c "string" demo_file #count the occurrence
echo -e "1 2 3 4\nhellow\n5 6" | grep -c "[0-9]"
grep -r  --exclude-dir=log "string" *
grep -c "[0-9]" demo_file

grep -o "[0-9]" demo_file | wc -l     #count no of times
echo -e "1 2 3 4\nhellow\n5 6" | grep -o "[0-9]" | wc -l
cat filename | grep -b -o "word"
grep -l "string" sample.txt sample1.txt     #with-match
grep -L "string" sample.txt sample1.txt     #without-match

grep "string" . -R -n       #recursive search
grep -i "string" demo_file #case insensitive
grep -i 'Model' /proc/cpuinfo
grep -e "count" -e "image" -o     #multiple patterns
grep "main()" . -r --include *.{c,cpp}
grep "main()" . -r --exclude "README"
grep "string" file* -lZ | xargs -0 rm -rf

grep -o "is.*line" demo_file      #matched string
grep -v -E '^\#|^$' demo_file #skips line beginning "#" or empty
grep -v -f file1 file2 > file.out    #diff of 2nd with 1st
find . -type f -exec grep -il 'string' {} \; #find in directory tree

grep authentication failure /var/log/secure-20200329
export GREP_OPTIONS='--color=auto' #to enable all the time
grep -i break-in autth.log | awk {'print $12'}
ping -c 1 | grep 'bytes from'
ping -c 1 | grep 'bytes from' | cut -d = -f 4

# find all files named "*.java,v" containing both 'prevayl' and 'jtable'
grep -li "jtable" $(find . -name "*.java,v" -exec grep -li "prevayl" {} \;)
egrep 'sting1|sting2|sting3|sting4' file.txt # all lines matching multiple patterns
locate -i calendar | grep Users | egrep -vi 'twiki|gif|shtml|drupal-7|java|PNG'
ps auxwww | grep httpd               # all processes containing 'httpd'
ps auxwww | grep -i java             # all processes containing 'java', ignoring case
ls -al | grep '^d'                        # list all dirs in the current dir
#printing lines before and after of matching
grep --context=6 "string" demo_file      #6 lines before and after


No comments:

Post a Comment