brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: grep -C 3 shows the lines around each match

Linux
~/tips/tip-grep-context-lines

grep -n -C 3 'segfault' /var/log/syslog

Shows a few lines before and after every match, so you see what led up to an error.

An error line on its own rarely tells the story. What happened just before it is usually the interesting bit, and scrolling through the file in less to find it gets old fast.

grep can print the neighbours for you. -A NUM adds lines after each match, -B NUM adds lines before it and -C NUM does both:

grep -n -C 3 'segfault' /var/log/syslog

Each match now comes with three lines above and three below, and -n puts the line number in front so you can jump to that spot in an editor. Between separate groups grep prints a line with --, which makes the blocks easy to tell apart. When two matches are close together, their context merges into one block instead of repeating lines.

I’d use -B more than the other two. A failed backup or a container that keeps restarting tends to log the cause a few lines before the line that says it failed, so something like grep -B 5 'exit code' backup.log gets you the cause and the result in one go.

One caveat: these options do nothing together with -o. grep only prints the matched text in that case and warns you that the context is ignored. And if the -- separators get in the way of a script, --no-group-separator leaves them out.

Further reading: grep(1) manual page

More Linux tips a2query -m rewrite renice -n 10 -p 4242 cat config.yml | xsel -ib xvfb-run -a your-program --some-flag dpkg --get-selections > packages.txt All Linux tips (261) All topics

Link