bash bash中字符串的多次替换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25996806/
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 substitutions on a string in bash
提问by Martin
I have a variable named inet
which contains the following string:
我有一个名为的变量inet
,其中包含以下字符串:
inet="inetnum: 10.19.153.120 - 10.19.153.127"
I would like to convert this string to notation below:
我想将此字符串转换为以下符号:
10.19.153.120 10.19.153.127
I could easily achieve this with sed 's/^inetnum: *//;s/^ -//'
, but I would prefer more compact/elegant solution and use bash. Nested parameter expansion does not work either:
我可以使用 轻松实现这一点sed 's/^inetnum: *//;s/^ -//'
,但我更喜欢更紧凑/优雅的解决方案并使用 bash。嵌套参数扩展也不起作用:
$ echo ${${inet//inetnum: /}// - / }
bash: ${${inet//inetnum: /}// - / }: bad substitution
$
Any other suggestions? Or should I use sed
this time?
还有其他建议吗?还是我应该利用sed
这个时间?
回答by Barmar
You can only do one substitution at a time, so you need to do it in two steps:
一次只能进行一次替换,因此需要分两步进行:
newinet=${inet/inetnum: /}
echo ${newinet/ - / }
回答by chepner
Use a regular expression in bash
as well:
也使用正则表达式bash
:
[[ $inet =~ ([0-9].*)\ -\ ([0-9].*)$ ]] && newinet=${BASH_REMATCH[@]:1:2}
The regular expression could probably be more robust, but should capture the two IP addresses in your example string. The two captures groups are found at index 1 and 2, respectively, of the array parameter BASH_REMATCH
and assigned to the parameter newinet
.
正则表达式可能更健壮,但应该捕获示例字符串中的两个 IP 地址。两个捕获组分别位于数组参数的索引 1 和 2 处,BASH_REMATCH
并分配给参数newinet
。