bash bash中变量的多个正则表达式替换?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7585564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
multiple regex replacement on variable in bash?
提问by tonybaldwin
I'd like to know if there's a way to make multilple regexp replacements in bash with ${string//substring/replacement} or, possibly, what better solution exists.
我想知道是否有办法在 bash 中使用 ${string//substring/replacement} 进行多个正则表达式替换,或者可能存在什么更好的解决方案。
I have a script to send updates to statusnet and friendika with curl. I sign petitions online, for instance, and am offered to tweet them, but would rather send to identica. I'm tired of pasting stuff and having to edit in terminal to escape @ and #, ! and ?. I'd like to regexp replace them in my script to automagically change
我有一个脚本可以使用 curl 将更新发送到 statusnet 和friendika。例如,我在网上签署请愿书,并被邀请在推特上发帖,但更愿意发送给 identica。我厌倦了粘贴内容并且不得不在终端中进行编辑以转义 @ 和 #, ! 和 ?。我想在我的脚本中用正则表达式替换它们以自动更改
@repbunghole and @SenatorArsehat Stop farking around with #someship! Do you want me to come smack you? | http://someshort.url
to
到
\@repbunghole \@SenatorArsehat Stop farking around with \#someship\! Do you want me to come smack you\? \| http://someshort.url
I do not have strong sed or awk fu, but imagine they may offer solutions, and I don't know how to use sed without writing the variable to a file, reading the file and acting on it, then setting the var with var=$(cat file). Yes. I'm pretty new at this stuff. I'm not finding sufficient data with the above ${string//substring/replacement/} for multiple replacements. Running that X times to escape X different characters seems inefficient.
我没有强大的 sed 或 awk fu,但想象他们可能会提供解决方案,而且我不知道如何使用 sed 而不将变量写入文件,读取文件并对其进行操作,然后使用 var= 设置 var= $(猫文件)。是的。我对这个东西很陌生。我没有用上面的 ${string//substring/replacement/} 找到足够的数据来进行多次替换。运行 X 次来转义 X 个不同的字符似乎效率低下。
like
喜欢
read -p "Enter a string: " a
b=${a//\@/\\@}
c=${b//\#/\\#}
d=${c//\!/\\!}
e=${d//\?/\\?}
f=${e//\"/\\"}
g=${f//\'/\\'}
etc., etc. works in the meantime, but it's ugly...
等等,等等同时工作,但它很难看......
回答by Tim Pietzcker
回答by Kent
for "multiple regex replacement on variable in bash?"
对于“bash 中变量的多个正则表达式替换?”
both sed and awk can do it. e.g I want to replace
sed 和 awk 都可以做到。例如我想更换
kent$ v=abc
kent$ newV=$(sed -e's/a/1/; s/b/2/; s/c/3/' <<< $v)
kent$ echo $newV2
123
with sed:
与sed:
kent$ v=abc
kent$ newV2=$(awk '{gsub(/a/,"1");gsub(/b/,"2");gsub(/c/,"3")}1' <<< $v)
kent$ echo $newV
123
with awk:
使用awk:
##代码##
