How to Substitute Expression Globally with Bash Bracket Substitution Syntax?

I want to use the bash syntax ${var/pattern1/pattern2} to replace the content of $var but for all matching patterns pattern1 instead of the first one.

$ A=aa 
$ echo ${A/a/b}
ba

I want to get bb instead of ba.

1 Answer

You can try this syntax which gives output:

$ A=aa 
$ echo ${A//a/b}
bb

${A//a/b} replaces all the matches of a with b. Whereas, ${A/a/b} will replace only 1st match of a.

More details about Bash Strings Manipulation can be found here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest