I want to use sed
's transliterate (y///
) to replace one set of characters by another.
I would expect this to work just as well as using the tr
program.
$ echo '[]{}abc' | tr '[ab}' 'gefh'
g]{hefc
However, when I go to perform this same operation with sed, I see the following error:
$ echo '[]{}abc' | sed 'y/[ab}/gefh/'
sed: 1: "y/[ab}/gefh/": unbalanced brackets ([])
This makes some sense, as I expect to need to escape the [
character. However, when I do try and escape that, I receive the following, different error:
$ echo '[]{}abc' | sed 'y/\[ab}/gefh/'
sed: 1: "y/\[ab}/gefh/": transform strings are not the same length
My current work-around is to either (1) just use tr
or (2) insert a "dummy character" in the right-hand side of the transliteration whose job is to do nothing but match the escape character.
$ echo '[]{}abc' | sed 'y/\[ab}/_gefh/'
g]{hefc
This is however unsatisfying and suspicious. It's also not very safe, e.g. when \
is in the input string.
$ echo '[]{}abc\' | sed 'y/\[ab}/_gefh/'
g]{hefc_
What's the correct way to escape a character in a sed transliteration without sed treating the escape character itself a part of the translation?