Linux · Systems fluency
How do grep and regular expressions work?
Short answer
grep prints lines that match a pattern. It supports basic, extended, and sometimes Perl-compatible regular expressions, with flags for case, inversion, recursion, filenames, and counts.
Regular expressions describe text patterns. Anchors match line boundaries, character classes match sets, and quantifiers repeat atoms. grep works line by line, so patterns do not span lines unless you use a tool designed for that.
grep -RniE "error|fail(ed)?" /var/log
rg -n "timeout" src/
grep -v "^#" app.confFlags worth knowing
- -i ignores case, -v inverts the match, and -n prints line numbers
- -r recurses through directories and -R follows symlinks
- -E enables extended regular expressions, while -P enables PCRE where available
- -o prints only the matched text, and -c counts matching lines
- -l lists filenames instead of matching lines
Overly broad patterns create false positives and expensive scans. Start with a narrow pattern, inspect sample output, then widen deliberately. Use word boundaries when searching for short identifiers that appear inside other words.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the difference between basic and extended regular expressions?
- 2How do you search recursively while ignoring binary files?
- 3When would you use grep -o instead of the default output?
- 4Why can a regular expression be slower on some inputs?
Say it in the interview
grep prints lines matching a pattern, and regex describes that pattern with anchors, classes, and quantifiers. I use -E for extended syntax, -r for directories, and -n for line numbers. I quote patterns and start narrow to avoid false positives. For codebases I usually reach for ripgrep because it respects ignore files.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Linux mock interview and get scored feedback on depth, clarity and confidence.