bash 中变量的多个正则表达式替换?
我想知道是否有办法在 bash 中进行多个正则表达式替换 ${string//substring/replacement} 或者,可能存在什么更好的解决方案。
我有一个脚本可以使用curl 向statusnet 和friendika 发送更新。 例如,我在网上签署请愿书,并被提议在推特上发布它们,但我宁愿发送到 identica。我厌倦了粘贴内容并必须在终端中编辑以转义@和#,!和 ?。 我想在我的脚本中用 regexp 替换它们以自动更改
@repbunghole and @SenatorArsehat Stop farking around with #someship! Do you want me to come smack you? | http://someshort.url
为
\@repbunghole \@SenatorArsehat Stop farking around with \#someship\! Do you want me to come smack you\? \| http://someshort.url
我没有强大的 sed 或 awk fu,但想象它们可能提供解决方案,并且我不知道如何使用 sed 而不将变量写入文件,读取文件并对其进行操作,然后使用 var=$(cat file) 设置 var。是的。我对这件事很陌生。 我在上面的 ${string//substring/replacement/} 中找不到足够的数据来进行多次替换。运行 X 次来转义 X 个不同的字符似乎效率很低。
像
read -p "Enter a string: " a
b=${a//\@/\\\@}
c=${b//\#/\\\#}
d=${c//\!/\\\!}
e=${d//\?/\\\?}
f=${e//\"/\\\"}
g=${f//\'/\\\'}
等等等等 同时工作,但它很丑......
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.
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
@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.
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这就是 字符类 的用途:
That's what character classes are for:
对于“bash 中变量的多个正则表达式替换?”
sed 和 awk 都可以做到。
替换
例如我想用 sed:
为 awk:
for "multiple regex replacement on variable in bash?"
both sed and awk can do it.
e.g I want to replace
with sed:
with awk: