2017-02-03 24 views
2

我有一個參數$1,例如設置爲字符串operations/software/tools-manifest,我想將其轉換爲字符串operations-software-tools-manifest,即我。即用破折號(-)替換所有斜槓(/)。單獨使用bash這可能嗎?例如sed(1)

我試過(unsucessfully):

[[email protected] ~]$ testparam=operations/software/tools-manifest 
[[email protected] ~]$ echo "${testparam////-/}" 
operations-/software-/tools-manifest 
[[email protected] ~]$ echo "${testparam///-/}" 
operations/software/tools-manifest 
[[email protected] ~]$ echo "${testparam//\//-/}" 
operations-/software-/tools-manifest 
[[email protected] ~]$ echo "${testparam//\\//-/}" 
operations/software/tools-manifest 
[[email protected] ~]$ echo "${testparam//[/]/-/}" 
operations/software/tools-manifest 
[[email protected] ~]$ echo "${testparam//\x2f/-/}" 
operations/software/tools-manifest 
[[email protected] ~]$ echo "${testparam//\57/-/}" 
operations/software/tools-manifest 
[[email protected] ~]$ 

回答

4

您可以使用"${testparam//\//-}"替換所有斜槓通過-

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

* argl *爲什麼我在測試中使用尾隨'/'?謝謝! –

4

一個最簡單,最通用的方式來做到這一點將你的源和目標放入變量中。

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

如果你也想抑制通配符,那麼你就需要引用"$in"(此當in='*'testparam='hello*cruel*world'工作):

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

如果沒有額外的報價,一單一*將擴展爲匹配整個輸入字符串,因此輸出將只包含-