4

I'm little bit confused about this statement(construction?). I cound't find any sufficient source about this (I do not even know how to call it). What is happening here?

bash-4.3$ var="a/b"
bash-4.3$ f=${var/b/c/\d}                                                                                                                                                                                                             
bash-4.3$ echo $f                                                                                                                                                                                                                     
a/c/d

or this:

bash-4.3$ var="b/a"                                                                                                                                                                                                                   
bash-4.3$ f=${var/b/c/\d}                                                                                                                                                                                                             
bash-4.3$ echo $f                                                                                                                                                                                                                     
c/d/a 

Thanks

3
  • 1
    I am not certain about the last part of the notation (\d), bit it appears to be concatenating it to the end after the substring substitution based on your examples. The construction ${FOO/a/b} means to take the variable FOO and replace the first occurrence of a with b (aaa would become baa).
    – DopeGhoti
    Jan 12 '16 at 17:40
  • 1
    @DopeGhoti I think someone meant to escape slash (f=${var/b/c\/d} rather than f=${var/b/c/\d})
    – TNW
    Jan 12 '16 at 17:47
  • TL;DR man bash Section Parametet Expansion SCNR
    – ott--
    Jan 12 '16 at 18:53
7

Read about bash's parameter expansion. In your examples you're using the search and replace syntax which substitutes the first occurrence of the given pattern.

${parameter/pattern/string}

Example:

> X="aaaa"
> echo ${X/a/b}   # substitute first occurence of a with b
> baaa

The syntax to replace all occurrences is:

${parameter//pattern/string}

Example:

> X="aaaa"
> echo ${X//a/b}   # substitute all occurences of a with b
> bbbb

Thus in your first example your parameter was "a/b" and you told bash to replace the first occurence of "b" in "a/b" (the value of var) with the string "c/d" (which results in "a/c/d"). Note that "\d" is unnecessarily escaped - no difference to "d" alone).

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.