如何在bash中用下划线和双引号替换空格 [英] how to replace spaces with underscore and doublequotes with nothing in bash

查看:90
本文介绍了如何在bash中用下划线和双引号替换空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的字符串如下:

$ echo "$val1"
"$29.95 Carryover Plan 1GB"

现在我可以使用此方法用下划线替换空格

Now I can use this method to replace the spaces with underscores

$ echo "NAME_"${val1// /_}"_NAME"
NAME_"$29.95_Carryover_Plan_1GB"_NAME

并且可以做同样的事情来替换"双引号而不添加任何内容

And can do the same for replacing " double quotes with nothing

$ echo "NAME_"${val1//'"'/}"_NAME"
NAME_$29.95 Carryover Plan 1GB_NAME

现在我可以使用sed进行相同的操作-用下划线替换空格

Now I can use sed to do the same - to replace the spaces with underscores

$ echo "$val1" | sed s/" "/_/g
"$29.95_Carryover_Plan_1GB"

然后我可以通过添加此 sed s/''/''/g

And I can then remove the double quotes by adding this sed s/'"'/''/g

$ echo "$val1" | sed s/" "/_/g | sed s/'"'/''/g
$29.95_Carryover_Plan_1GB

所以这就是我想要的(用下划线和双引号代替的空格),但是我可以使用上面的第一种方法来实现它吗?

So this is what I want (spaces repalaced with underscore and double quotes removed) but can i achieve it using my first approach above e.g.

$ echo "NAME_"${val1// /_}"_NAME"
NAME_"$29.95_Carryover_Plan_1GB"_NAME

这是我的尝试

$ echo "NAME_"${${val1// /_//'"'/}}"_NAME"
-sh: "NAME_"${${val1// /_//'"'/}}"_NAME": bad substitution

edit1 这是我可以实现的功能,但我希望能够通过第一种方法来实现.

edit1 this is the sed I can achieve but I want to be able to achieve this by my first approach

$ echo "NAME_"$val1"_NAME" | sed s/" "/_/g | sed s/'"'/''/g
NAME_$29.95_Carryover_Plan_1GB_NAME

推荐答案

由于在 $ {var/sub/rep} 中的第一个参数,因此无法在变量上嵌套字符串操作操作是变量名,而不是字符串.

There is no way to nest string manipulation operations on a variable because the first parameter in the ${var/sub/rep} is a variable name, not a string.

NAME='"$29.95 Carryover Plan 1GB"'
NAME=${NAME// /_}
NAME=${NAME//\"/}

巧合的是, sed 是一种脚本语言.您可以在一个脚本中简单地执行多个替换.请参阅组合2个sed命令.

Coincidentally, sed is a scripting language; you can trivially perform multiple substitutions in one script. See combining 2 sed commands.

这篇关于如何在bash中用下划线和双引号替换空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆