8

I saw the following substitution in this article:

${PWD/#$HOME/~}

How does it compare to this?

${PWD/$HOME/~}

Both seem to be the same. I don't know why the hash was included.

2 Answers 2

9

man bash, explanation for ${parameter/pattern/string}:

If pattern begins with #, it must match at the beginning of the expanded value of parameter. If pattern begins with %, it must match at the end of the expanded value of parameter.

> var=abcd
> echo "${var/bc/_}"
a_d
> echo "${var/#bc/_}"
abcd
4

Speaking about pattern matching and substitution in short for the ${parameter/pattern/string} format with some examples:

If the pattern begins with /, all matches of pattern are replaced with string. Normally only the first match is replaced.

> test=test
> echo ${test//t/-} 
> -es-

If pattern begins with #, it must match at the beginning of the expanded value of parameter.

> test=test
> echo ${test/#t/-}
> -est

If pattern begins with %, it must match at the end of the expanded value of parameter.

> test=test
> echo ${test/%t/-}
> tes-

An example with using asterix *:

> test=test
> echo ${test/#*es/-}
> -t

Reference: man bash: ${parameter/pattern/string}

1
  • Damn, this isn't consistent with regular expressions Commented May 21 at 21:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .