- Search for string in a file
$ grep root /etc/passwd
root:x:0:0:root:/root:/bin/bash
$ grep -i ROOT /etc/passwd
# -i is for case insensitive
root:x:0:0:root:/root:/bin/bash
$ grep -i "gnats bug" /etc/passwd
# you can wrap the search string around quotes
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
$ grep -w ro /etc/passwd
# why didn't it match root? -w whole word matching only
$
$ grep -c root /etc/passwd
# -c for count
1
$ grep -n root /etc/passwd
# -n for line number
1:root:x:0:0:root:/root:/bin/bash
2. Recursive use of grep
$ grep -r "mydomain.com" /etc/nginx/
/etc/nginx/sites-available/mydomain.com.vhost: if ($http_host != "www.mydomain.com") {
3. Multiple matches
$ egrep "root|news" /etc/passwd
root:x:0:0:root:/root:/bin/bash
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
4. Invert match
grep -v root /etc/passwd
prints everything except for lines with root
5 Match multiple patterns
$ grep -e root -e news /etc/passwd
root:x:0:0:root:/root:/bin/bash
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
6 Quiet output - good for coding
$ grep -q root /etc/passwd
$ echo $?
0
7. Recursive search
$ grep -d recurse root /etc
.....