mcintyre321
mcintyre321

Reputation: 13306

How does this bash string manipulation work?

I'm a bit confused by a bash script I'm working with. Here's a simplified bit of the syntax/operation that's confusing me:


STACKDIR="/Users/my.name/projects/someproject"
WORKDIR="/Users/my.name/projects/someproject/foo/bar/baz"
SUBPATH="${WORKDIR/$STACKDIR\//}"
echo $STACKDIR
echo $WORKDIR
echo $SUBPATH

this outputs

/Users/my.name/projects/someproject
/Users/my.name/projects/someproject/foo/bar/baz
foo/bar/baz

how does SUBPATH="${WORKDIR/$STACKDIR\//}" work to remove STACKDIR from the start of WORKDIR?

Upvotes: 1

Views: 86

Answers (3)

dreygur
dreygur

Reputation: 338

It's substring replacement.

See ${string/substring/replacement}

More to be clear:

$ string="HELLO"
$ echo ${string/"LL"/"ll"}
$ HEllO

More at: Manipulating-Strings

Upvotes: 1

agentsmith
agentsmith

Reputation: 1326

Have a look at Shell-Parameter-Expansion

See ${parameter/pattern/string}

From the link above: The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string.

The double \\are replaced as one \

Hope this helps.

Addendum: It's not specified by POSIX. Not all Unix shells implement it.

Upvotes: 2

Diego Torres Milano
Diego Torres Milano

Reputation: 69208

It's a substitution.

This example would clarify it

$ v="abc"
$ echo ${v/b/d}
adc

Upvotes: 0

Related Questions