Teekeks
Teekeks

Reputation: 196

removing tailing and leading strings from variable in one step

I have a string in the var f that is "res/some/path/file.ext.patch" and I want to remove the ".patch" and the "res/". That means I expect the result to be "some/path/file.ext".

I know that I can remove the leading "res/" with ${f#res/} and the tailing ".patch" with ${f%.patch}

I want to replace both in one step without using a temp variable so I tried this: ${${f#res/}%.patch} but I get the following error:

/bin/bash: ${${f#res/}%.patch}: Wrong variable substitution.

What

Upvotes: 0

Views: 48

Answers (1)

chepner
chepner

Reputation: 532478

Parameter expansion operators cannot be chained. The closest you can come to doing this in one step is to use a regular expression match.

[[ $f =~ res/(.*).patch ]] && f=${BASH_REMATCH[1]}

I leave it up to you if that is preferable to

f=${f#res/}
f=${f%.patch}

Upvotes: 2

Related Questions