Today I needed to remove backslashes from a number of files.
I have yaml frontmatter that should look like this:
I had some files that had backslashes before the dash:
You can use Unix tools like grep or sed to search all files that match a pattern. Then you can replace that pattern.
But you have to remember that a backslash is a special character. It’s used as an escape hatch to escape other expressions.
Matching a backslash means you have to double it:
That makes search and replace very confusing when you run it from the shell as you have to “double” escape - once for the shell and once for the regex.
Here’s how to search all files in a directory for
\ - and delete the backslash in the fish shell:
grep -rl '\\\-' | xargs sed -i 's/\\\//g'
grep -rl runs the search recursively in the current folder and outputs matching files.
xargs pipes the output of grep to sed.
sed -i uses sed to replace the backslash with an empty expression (delete it), inplace.
If you want to use alternative tools written in Rust:
rg '\\\-' --files-with-matches | xargs sd '\\\' ''
Or using ruplacer:
ruplacer '\\\\-' '' .