linuxsed

How to use sed to replace multiple chars in a string?


I want to replace some chars of a string with sed.

I tried the following two approaches, but I need to know if there is a more elegant form to get the same result, without using the pipes or the -e option:

sed 's#a#A#g' test.txt | sed 's#l#23#g' > test2.txt
sed -e 's#a#A#g' -e 's#l#23#g' test.txt > test2.txt

Solution

  • Instead of multiple -e options, you can separate commands with ; in a single argument.

    sed 's/a/A/g; s/1/23/g' test.txt > test2.txt
    

    If you're looking for a way to do multiple substitutions in a single command, I don't think there's a way. If they were all single-character replacements you could use a command like y/abc/123, which would replace a with 1, b with 2, and c with 3. But there's no multi-character version of this.