Andy's Cafe

Use `rg` for Find and Replace

Last updated :

How to do the thing

  1. Include a -o to limit the output to things that match
  2. Use any number of capture groups in your search string
  3. Include a -r 'my-replacement-string' and use $x in my-replacement-string to reference your capture groups
    • $x starts at 1

Example

Say you have a log file and want to just match the date at the start of the line.

cat my-file-to-search \
    | rg -o '^(\d+-\d+-\d+).*' \
         -r '$1'

I didn’t actually test this, but it should work.

Thoughts

This is the sort of thing that you would probably think to reach for grep and sed to do.

But I think sed is a bit complicated and I tend to get bit by the differences between GNU sed and BSD sed.

So when I found out rg can handle this too, I was happy to switch.

Reply via email

Tags

#shell-stuff