Skip to content

Search inside files: grep

Search files with grep, ignore case with -i, add line numbers with -n, count matches with -c and filter other commands. Practise on a real-looking log.

Lesson 13 of 167 minSkip to the terminal ↓

grep searches text and prints only the lines that contain a pattern:

grep INFO logs/server.log

Matches are highlighted in red. grep is case-sensitive, so grep error misses lines that say ERROR. That's what the options are for:

OptionDoes
-iignore case: error, Error and ERROR all match
-nshow line numbers
-ccount the matching lines instead of printing them
-vinvert: print the lines that don't match
-wwhole words only
grep -in error logs/server.log
grep -c WARN logs/server.log

Several files, and pipes

Give grep several files (or a wildcard) and it puts each file's name in front of its matches:

grep flour recipes/*.txt

grep is also the most common filter in pipelines. ls | grep .txt keeps the names with .txt, and grep WARN logs/server.log | wc -l counts warnings the long way.

Put the pattern in quotes when it has spaces or special characters: grep "not found" logs/server.log.

Your task

Show every line in logs/server.log that mentions an error, however it’s capitalised, then count how many lines contain WARN.

  • Every error line, in any case (not done yet)
  • Count the WARN lines (3) (not done yet)

Lesson 13 of 16.

learner@sandbox: ~bash (practice)
Note: Practice shell for this lesson. Type a command and press Enter (help lists them all).