Tim Landscheidt
Tim Landscheidt

Reputation: 1400

Replace "/" in string with "${parameter/pattern/string}"?

I have a parameter $1 that for example is set to the string operations/software/tools-manifest and I want to transform that to the string operations-software-tools-manifest, i. e. replace all slashes (/) with dashes (-). Is this possible with bash alone, not calling for example sed(1)?

I tried (unsucessfully):

[tim@passepartout ~]$ testparam=operations/software/tools-manifest
[tim@passepartout ~]$ echo "${testparam////-/}"
operations-/software-/tools-manifest
[tim@passepartout ~]$ echo "${testparam///-/}"
operations/software/tools-manifest
[tim@passepartout ~]$ echo "${testparam//\//-/}"
operations-/software-/tools-manifest
[tim@passepartout ~]$ echo "${testparam//\\//-/}"
operations/software/tools-manifest
[tim@passepartout ~]$ echo "${testparam//[/]/-/}"
operations/software/tools-manifest
[tim@passepartout ~]$ echo "${testparam//\x2f/-/}"
operations/software/tools-manifest
[tim@passepartout ~]$ echo "${testparam//\57/-/}"
operations/software/tools-manifest
[tim@passepartout ~]$

Upvotes: 2

Views: 134

Answers (2)

Charles Duffy
Charles Duffy

Reputation: 295500

One of the easiest, most general-purpose ways to do this is to put your source and destination in variables.

in="/"
out="-"
testparam=operations/software/tools-manifest
echo "${testparam//$in/$out}"

If you want to also suppress globbing (for this to work when in='*' and testparam='hello*cruel*world'), then you need to quote "$in":

in="*"
out="-"
testparam='operations*software*tools'
echo "${testparam//"$in"/$out}"

Without the extra quotes, a single * will expand to match the entire input string, so the output will contain only -.

Upvotes: 4

anubhava
anubhava

Reputation: 785276

You can use "${testparam//\//-}" to replace all the forward slashes by -:

echo "${testparam//\//-}"
operations-software-tools-manifest

Upvotes: 4

Related Questions