12

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
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
neo33
  • 1,809
  • 5
  • 18
  • 41

3 Answers3

23

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
6

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

kshpolvind
  • 91
  • 4
2

When you have a lot strings for the replacement, you can collect them in a variable.

seds="s/a/A/;"
seds+="s/1/23/;"
echo "That was 1 big party" |
   sed ${seds}
Walter A
  • 19,067
  • 2
  • 23
  • 43