Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

456
Views
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
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report

0

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}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!