Replace content in files with ripgrep

Linux

Spoiler: ripgrep cannot do this standalone. But you can combine it with other tools to achieve this.

The problem

I use Obsidian with frontmatter (YAML) to track my journal along with some statistics. Sometimes I miss adding all data and want to fill the gaps with the last measurement. Bear with me: I know not correct in a mathematical sense but it is good enough for me. When my note is automatically generated a default value is used.

The solution

Assumption: use a weight property, defaulting to 0.

ripgrep

I used a combination of ripgrep and sponge to achieve this in fish:

for f in (rg -u -u -l -- 'weight: 0')
  cat $f | rg --passthrough -r 'weight: 1' -- 'weight: 0' | sponge $f
end

Alternate solution (untested)

rg -l 'old' | xargs sed -i 's/old/new/g'