简体   繁体   English

Linux shell 多次出现的字符串替换

[英]Linux shell string substitution with multiple occurrences

When I use the shell string substitution mechanism, only the first occurrence is replaced.当我使用 shell 字符串替换机制时,只会替换第一次出现的位置。

For instance, If I try to replace the substring @folder with substring mypod in the string:例如,如果我尝试将字符串中的 substring @folder替换为 substring mypod

hostname | grep @folder && cat /etc/hosts | grep @folder

I get我得到

hostname | grep mypod && cat /etc/hosts | grep @folder

Here is what I tried:这是我尝试过的:

root@mypod:/# export var="hostname | grep @folder && cat /etc/hosts | grep @folder"
root@mypod:/# echo $var                                                            
hostname | grep @folder && cat /etc/hosts | grep @folder
root@mypod:/# var2=${var/@folder/mypod}
root@mypod:/# echo $var2
hostname | grep mypod && cat /etc/hosts | grep @folder

What am I missing?我错过了什么?

Thanks in advance提前致谢

${var/@folder/mypod} should be ${var//@folder/mypod} ${var/@folder/mypod}应该是${var//@folder/mypod}

If you are using bash, here you have a guide on variables expansion you might find useful.如果您使用的是 bash, 这里有一份变量扩展指南,您可能会觉得有用。

From the bash man-page, section Parameter Expansion : the longest match of pattern against its value is replaced .来自 bash 手册页的参数扩展部分:模式与其值的最长匹配被替换 It does not say "all matches are replaced"它没有说“所有比赛都被替换”

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

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