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 -m 1 stops reading after the first match

Linux
~/tips/tip-grep-max-count

grep -n -m 1 'Out of memory' /var/log/syslog

Makes grep quit after the first match, or after any number you choose.

Sometimes one hit is all I need: does this huge log contain the error at all, or what’s the first line where it showed up. Plain grep still reads every last byte of the file to give you all the other matches you didn’t ask for.

-m NUM (long form --max-count) makes grep stop reading a file after NUM matching lines:

grep -n -m 1 'Out of memory' /var/log/syslog

That gives you the first out-of-memory line with its line number and then grep quits. On a big file that’s a lot faster than reading to the end. It also works the other way around with tac, which reverses the file, so tac /var/log/syslog | grep -m 1 'Out of memory' shows the most recent one.

It combines well with -c too. grep -c -m 10 counts up to ten matching lines and stops, which is enough to answer “is this happening a lot?” without counting a million lines.

Two caveats. The limit is per file, so with -r or several file names you get up to NUM matches from each file, not NUM in total. And it counts matching lines, not matches: a line with the word three times still counts as one.

Further reading: grep(1) manual page

Going deeper: Run degoog on Unraid as your own search page, compared with SearXNG and 4get

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