Abdelghani
Abdelghani

Reputation: 745

Linux shell string substitution with multiple occurrences

When I use the shell string substitution mechanism, only the first occurrence is replaced.

For instance, If I try to replace the substring @folder with substring mypod in the string:

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

Upvotes: 1

Views: 179

Answers (2)

user1934428
user1934428

Reputation: 22225

From the bash man-page, section Parameter Expansion: the longest match of pattern against its value is replaced. It does not say "all matches are replaced"

Upvotes: 0

Miguel
Miguel

Reputation: 2219

${var/@folder/mypod} should be ${var//@folder/mypod}

If you are using bash, here you have a guide on variables expansion you might find useful.

Upvotes: 3

Related Questions