sed: how to replace \0, but not \\0

backslash, regex, sed

Solution

First, you can make the regex only match `\0` when it follows something other than `\`

$ echo '320.48k\\02. Easy Listening' | sed 's/\([^\\]\)\\0/\1 /g'
320.48k\\02. Easy Listening

That fixes the problem, but it fails when `\0` is at the start of the line, so make the preceding match optional:

$ echo '\0320.48k\\02. Easy\0Listening' | sed 's/\([^\\]\)\?\\0/\1 /g'
 320.48k\ 2. Easy Listening

This doesn't work though, because `\\0` can match the regex with zero occurences of the parenthesised sub-group.

Another alternative is to say the `\0` must either come at the start of the line, or the preceding character must not be `\`

$ echo '\0320.48k\\02. Easy\0Listening' | sed 's/\([^\\]\|^\)\\0/\1 /g'
 320.48k\\02. Easy Listening

(As a comment points out, this still gives the wrong result for odd numbers of backslashes.)

Problem

I'm doing a migration from mysql to postgres. As part of that I'm processing the mysql dump using sed before loading that into postgres. My MySQL dump has some `\0` characters and postgres doesn't like them. So I'm replacing them using a space. ``` sed 's/\\0/ /g' $dumpfile ``` Noticed an issue when the line has `320.48k\\02. Easy Listening`. ``` $ echo '320.48k\\02. Easy Listening' | sed 's/\\0/ /g' 320.48k\ 2. Easy Listening ``` Thats not what I quite wanted. `\\` characters are followed by `0` is not a null character. and I want to keep as it is. Any sed experts around to help?

Original source