Pages

21/09/2019

[bash] String substitution with parameter expansion

In bash, it is possible to use parameter expansion with syntax ${expression} to perform a string replace. Here are some examples, the first value MUST be a variable.

To replace ONE occurrence of substring:

result=${string/substring/replace_with}

For example

string=grogblog
result=${string/blog/logs}

will return groglogs

To replace ALL occurrences of substring:

result=${string//substring//replace_with}

For example

string=grogbloggrogblog
result=${string//blog/logs}

will return groglogsgroglogs

Note the difference is simply the // instead of / at the beginning

No comments:

Post a Comment

With great power comes great responsibility