Difference between revisions of "Linux comand: grep"

From RHS Wiki
Jump to navigation Jump to search
m
Tag: visualeditor
Tag: visualeditor
 
(One intermediate revision by the same user not shown)
Line 61: Line 61:
  
 
==Grep with blanks==
 
==Grep with blanks==
cat dig_output.txt | grep -E 'IN[[:blank:]]A'
+
<syntaxhighlight lang="bash">
 +
cat dig_output.txt | grep -E 'INblank:A'
 +
cat LogsAndreaPasswords.csv | awk -F ',' '{print $1 "," $2}' | uniq -c | sort -n | grep '^\s*1 '
 +
</syntaxhighlight>
 +
 
 +
==Grep remove comments and blank lines==
 +
<syntaxhighlight lang="bash">
 +
cat file.txt | grep -v ^\#|grep .
 +
</syntaxhighlight>

Latest revision as of 07:21, 28 January 2020

Command-line utility to search lines matching regular expresions in plain-text data sets.

Option Description Example
-c Count grep -c 'root' /etc/passwd
-e Specify multiple search patterns grep -e 'root' -e 'system' /etc/passwd
-r Recursive
-v Show lines not matching the pattern
-i Case insensitive
-n Output line numbering
-E Enable regex use (similar to egrep)
-o Show only the match, not the full line
-f FILE Specify file to search in.
-H Print file name
-P Perl Regex grep -P '\d{16}'

Examples:

curl myip.is | grep -oE "\b([0-9]{1,3}.){3}[0-9]{1,3}\b" # grep IP Address
grep '\<a.*\>' archivo
cat archivo | grep "\<a.*\>"
grep "#" /boot/grub/menu.lst
grep -v "#" /boot/grub/menu.lst
grep -c "iface" /etc/network/interfaces
grep -e "root" -e "password" archivo
grep -n -e "root" -e "password" archivo
grep -r "password" *
ifconfig eth0 | grep -oiE '([0-9A-F]{2}:){5}[0-9A-F]{2}' # Show eth0 MAC address
grep -Eio '[a-z0-9._-]+@[a-z0-9.-]+[a-z]{2,4}' file.txt  # Extract e-main addresses from file.txt

Find files containing text pattern

grep -rnw '/path/' -e "pattern"
  • -r or -R is recursive,
  • -n is line number, and
  • -w stands match the whole word.
  • -l (lower-case L) can be added to just give the file name of matching files.
--exclude or --include parameter could be used for efficient searching. Something like below:
grep --include=\*.{c,h} -rnw '/path/to/somewhere/' -e "pattern"
grep --exclude=*.o -rnw '/path/to/somewhere/' -e "pattern"
grep --exclude-dir={dir1,dir2,*.dst} -rnw '/path/to/somewhere/' -e "pattern"

Remove comments and blank lines

cat /etc/apache2/sites-enabled/default-ssl.conf | grep -v '^$\|^\s*\#'

Grep with blanks

cat dig_output.txt | grep -E 'INblank:A'
cat LogsAndreaPasswords.csv | awk -F ',' '{print $1 "," $2}' | uniq -c | sort -n | grep '^\s*1 '

Grep remove comments and blank lines

cat file.txt | grep -v ^\#|grep .