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: rg -o -r pulls just the part of a line you care about

CLI
~/tips/tip-ripgrep-only-matching-replace

rg -o -r '$2' '"(GET|POST) (\S+)' access.log

Prints only a captured piece of each match, such as the path from a log line.

A log line has a dozen fields and I usually want one. I used to reach for awk or a pipe of cut, but ripgrep can do the extraction itself when you give it a replacement.

rg -o -r '$2' '"(GET|POST) (\S+)' access.log

-o prints only the matched part of each line. -r (short for --replace, not recursive) swaps that match for the text you give it, and the text can refer to capture groups as $1, $2 and so on. Together they print only group 2. Given three lines of a web server log, ripgrep 14.1.0 printed this:

/index.html
/missing
/login

When you search a single file, ripgrep leaves out the file name. Search a folder and every line gets its file name in front, so add --no-filename when you want clean output for the next command. That makes a quick count possible:

rg -o -r '$2' --no-filename '"(GET|POST) (\S+)' access.log | sort | uniq -c

Without -o, -r only replaces the matched part inside the whole line, and the rest of the line stays.

One caveat: the replacement only changes what ripgrep prints. The guide says ripgrep never modifies your files, so this is not a find-and-replace for a file on disk. Quote the pattern and the replacement in single quotes, or your shell will expand $2 before ripgrep sees it.

Further reading: ripgrep user guide: replacements, rg(1) manual

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

More CLI tips wsl --shutdown wsl --distribution <Distribution Name> --user <User Name> Compress-Archive -Path C:\Reference -DestinationPath C:\Archives\Draft.zip wsl --terminate <Distribution Name> redis-cli --json HGETALL user All CLI tips (60) All topics

Link