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 -w matches whole words, so log stops matching login

Linux
~/tips/tip-grep-word-regexp

grep -w port /etc/ssh/sshd_config

Only matches your search term as a whole word, not inside longer words.

Search a config for port and grep also hands you export, support and transport. Search for a user called ed and it’s even worse. The pattern matches anywhere inside a word, which is rarely what I mean.

-w (long form --word-regexp) only keeps lines where the match stands as a whole word:

grep -w port /etc/ssh/sshd_config

Now Port 22 shows up and GatewayPorts doesn’t. grep checks that the match is at the start of the line or has a non-word character before it, and the same at the end. Word characters are letters, digits and the underscore.

Here’s a quick example you can paste in:

printf 'log\nlog-file\nlogin\nsyslog\n' | grep -w log

That prints log and log-file, and leaves out login and syslog.

Which is also the caveat. A hyphen, a dot or a slash isn’t a word character, so log-file still counts as containing the word log. If you need the line to be exactly your text and nothing else, use -x instead, which matches the whole line. My advice is to reach for -w when you search short names like ports, users or variables, because those are the ones that hide inside longer words.

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