Lesson 7.1: Searching text with grep
grep in depth: searching files and logs for a pattern, counting (-c), line numbers (-n), ignoring case (-i), whole words (-w), inverting the match (-v), several patterns (-E), searching directory trees (-r, -l), printing only the match (-o) and showing context (-A, -B, -C).
17 min
You will learn to
- Explain what grep prints and what its exit status means
- Count, number and case-fold matches
- Match whole words and invert a search
- Search a whole directory tree and list only file names
- Extract just the matching text and count it in a pipeline
- Show lines around a match
Key terms
- grep
- Prints the lines of its input that match a pattern. The name comes from the ed editor command g/re/p: globally search for a regular expression and print.
- Pattern
- What grep looks for. Plain text matches itself; some characters such as . * ^ $ [ ] have special meanings (regular expressions, section 10). Put patterns in single quotes so the shell leaves them alone.
- Exit status of grep
- 0 if at least one line matched, 1 if none matched, 2 if there was an error (for example a missing file). Scripts use this to decide what to do.
- auth.log
- The Debian/Ubuntu log for authentication: SSH logins, sudo use, su and password changes. Readable by root and the adm group.
- Options covered
- -c count · -n line numbers · -i ignore case · -w whole word · -v invert · -E extended patterns · -r recursive · -l file names only · -o only the match · -A/-B/-C N lines of context.
← Command substitution · All lessons · Transforming text: cut, tr, sed and awk →