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

18,811

Solution 1

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.

Solution 2

In addition to the answer of Barmar, you might want to use regexp character classes to perform several chars to one specific character substitution.

Here's an example to clarify things, try to run it with and without sed to feel the effect

echo -e 'abc\ndef\nghi\nklm' | sed 's/[adgk]/1/g; s/[behl]/2/g; s/[cfim]/3/g'

P.S. never run example code from strangers outside of safe sandbox

Share:
18,811
neo33
Author by

neo33

Updated on July 29, 2022

Comments

  • neo33
    neo33 over 1 year

    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