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 -o prints only the part of the line that matched

Linux
~/tips/tip-grep-only-matching

grep -oE '([0-9]{1,3}\.){3}[0-9]{1,3}' /var/log/auth.log

Prints only the matched text, like IP addresses, instead of the whole log line.

Plain grep gives you the whole line, and with log files that’s usually a wall of text when all you wanted was the IP address, the error code or the URL hiding somewhere in the middle.

Add -o (long form --only-matching) and grep prints just the matched text. If one line has two matches, you get two output lines. Pair it with -E for extended regular expressions and you have a quick extractor:

grep -oE '([0-9]{1,3}\.){3}[0-9]{1,3}' /var/log/auth.log

That pulls every IPv4-looking address out of the SSH log, one per line. On its own that’s a long list, so I’d pipe it on to count the noisiest ones:

grep 'Failed password' /var/log/auth.log | grep -oE '([0-9]{1,3}\.){3}[0-9]{1,3}' | sort | uniq -c | sort -rn | head

The first grep picks the failed logins, the second one cuts out the address, and the rest counts and ranks them. This is the kind of one-liner I’d want on a server that has SSH open to the internet.

The caveat: the pattern is only as smart as you make it. The one above happily matches 999.999.1.1, because it only checks for digits and dots. For a quick look at a log that’s fine; for anything you feed into a firewall rule, check the results. Also, -o and the context options like -A don’t mix: grep ignores the context and gives a warning.

Further reading: grep(1) manual page, GNU grep manual

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