Reputation: 1400
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
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
Reputation: 785276
You can use "${testparam//\//-}"
to replace all the forward slashes by -
:
echo "${testparam//\//-}"
operations-software-tools-manifest
Upvotes: 4