Essential Grep Commands
Here are 25 examples of the grep command, each with a brief explanation and an example of the output.
The examples use a sample file named example.txt which contains the following text:
Hello World This is a test file. GREP is a powerful tool. line 1: cat dog bird Line 2: fish mouse This line contains the word test. 12345 testing is fun This is another line.
To find lines containing the pattern test.
$ grep "test" example.txt This is a test file. This line contains the word test.
Use the -i option to ignore case, finding lines with "Test," "TEST," or "tEsT."
$ grep -i "test" example.txt This is a test file. This line contains the word test. testing is fun
$ grep -v "test" example.txt Hello World GREP is a powerful tool. line 1: cat dog bird Line 2: fish mouse 12345 This is another line.
$ grep -c "line" example.txt 2Use the -n option to show the line number for each match.
$ grep -n "line" example.txt 4:line 1: cat dog bird 6:This line contains the word test. 9:This is another line.
$ grep -w "test" example.txt This is a test file. This line contains the word test.
$ grep -x "12345" example.txt 12345
$ grep -r "Hello" . ./example.txt:Hello World
$ grep -l "test" *.txt example.txt
$ grep -L "Hello" *.txt another_file.txt
$ grep -E "dog|mouse" example.txt line 1: cat dog bird Line 2: fish mouse
$ cat example.txt | grep "World" Hello World
$ grep -B 1 "bird" example.txt GREP is a powerful tool. line 1: cat dog bird
$ grep -A 1 "dog" example.txt line 1: cat dog bird Line 2: fish mouse
$ grep -C 1 "dog" example.txt GREP is a powerful tool. line 1: cat dog bird Line 2: fish mouse
$ grep -q "World" example.txt && echo "Pattern found" || echo "Pattern not found" Pattern found
$ grep -F "GREP" example.txt GREP is a powerful tool.
$ grep "^$" example.txt (empty output because example.txt has no blank lines)
$ grep "^This" example.txt This is a test file. This line contains the word test. This is another line.
$ grep "World$" example.txt Hello World
$ cat patterns.txt test fish $ grep -f patterns.txt example.txt This is a test file. Line 2: fish mouse This line contains the word test. testing is fun
$ grep -o "is" example.txt is is is is
$ grep "[0-9]" example.txt line 1: cat dog bird Line 2: fish mouse 12345
$ grep "Hello" file1.txt file2.txt file1.txt:Hello World
$ grep "\$" example.txt (empty output because example.txt has no dollar signs)
grep -oh '[^"]*\.html' filename
Or if you want to be more specific and match quoted strings:
bash
grep -oh '"[^"]*\.html"' filename
Explanation:
-o = only output the matching part (not the whole line)
-h = suppress filename in output (useful with multiple files)
[^"]*\.html = matches any characters except quotes, followed by .html
The \. escapes the dot so it matches a literal period
If you want to remove the quotes from the output, you can pipe it through sed:
bash
grep -oh '"[^"]*\.html"' filename | sed 's/"//g'
Try the first one - it should grab all your .html filenames!