简体   繁体   English

如何使用sed替换字符串中的多个字符?

[英]How to use sed to replace multiple chars in a string?

I want to replace some chars of a string with sed. 我想用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: 我尝试了以下两种方法,但是我需要知道是否存在更优雅的形式来获得相同的结果,而无需使用管道或-e选项:

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

Instead of multiple -e options, you can separate commands with ; 您可以使用;分隔命令,而不是使用-e选项; 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 . 如果它们都是单字符替换,则可以使用y/abc/123类的命令,该命令将a替换a 1b替换a 2c替换为3 But there's no multi-character version of this. 但是,这没有多字符版本。

In addition to the answer of Barmar, you might want to use regexp character classes to perform several chars to one specific character substitution. 除了Barmar的答案外,您可能还想使用regexp字符类对一个特定的字符替换执行几个字符。

Here's an example to clarify things, try to run it with and without sed to feel the effect 这是一个澄清事物的示例,尝试在不使用sed情况下运行它,以感觉到效果

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

PS never run example code from strangers outside of safe sandbox PS永远不会在安全沙箱外部运行来自陌生人的示例代码

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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM