Here is another command that I keep forgetting the syntax for so I decided to make a page with examples to use.
Find text in a file. Displays the row where the text ‘root’ is found in file /etc/group
grep root /etc/group
Find text in a file. Display row and row number in file
grep -n root /etc/group
Find text in many files. Display filename and rows
grep -r root /etc/* #You can combine 'r' and 'n' with -rn (or -nr)
Find rows in a file that starts with a specific text. Displays all rows in file /etc/group where the row starts with the text ‘root’
grep ^root /etc/group
Find rows in a file that ends with a specific text. Displays all rows in file /etc/group where the row ends with the text ‘0:’
grep 0:$ /etc/group
Find a word in a row. A word is text that has a space or non-alpha characters in the beginning and the end. Displays all rows that contains the word ‘root’ in the file /etc/group
grep -w root /etc/group
Return rows before a found row.This will return all rows that contains the word ‘root’ AND the 2 closest rows above that row
grep -B2 root /etc/group
Return rows after a found row.This will return all rows that contains the word ‘root’ AND the 2 closest rows below that row
grep -A2 root /etc/group
NOTE: A and B can be combined to fetch more rows both below and above the matched row
Find rows that contains any of the specified characters. Display all rows that have one or more of the characters ‘0’,’1′,’2′,’a’,’b’,’c’ in file /ect/group
grep [0-2a-c] /etc/group # or [012abc]. Note case-sensitive!
Find all rows with exact number of wildcards. This will find all rows with text that starts with ‘r’ and ends with ‘t’ AND have exactly 2 wildcard characters in the middle. Display rows
grep '<r..t>' /etc/group
Note escaping of the < and > characters
Find all rows with wildcards. This will find all rows with text that start with ‘r’ and ends with ‘t’ AND have zero or more characters in between.
grep '<r.*t>' /etc/group
0 Comments.