我在腳本中有一個字符串變量 ,我想要做的是用/替換所有「 - 」,之後,我應該得到以下內容字符串如何使用shell替換特殊字符按字符
x=tmp/variable/custom/sqr/sample/test/example
任何人都可以幫助我嗎?
我嘗試下面的語法 它因此未工作
exa=tmp/variable/custom-sqr-sample/test/example
exa=$(echo $exa|sed 's/-///g')
我在腳本中有一個字符串變量 ,我想要做的是用/替換所有「 - 」,之後,我應該得到以下內容字符串如何使用shell替換特殊字符按字符
x=tmp/variable/custom/sqr/sample/test/example
任何人都可以幫助我嗎?
我嘗試下面的語法 它因此未工作
exa=tmp/variable/custom-sqr-sample/test/example
exa=$(echo $exa|sed 's/-///g')
基本的sed支持任何分隔符,其中就派上用場了,當一個人試圖匹配/
,最常見的是|
,#
和@
,挑選一個是不在你需要處理的字符串中。
$ echo $x
tmp/variable/custom-sqr-sample/test/example
$ sed 's#-#/#g' <<< $x
tmp/variable/custom/sqr/sample/test/example
在你上面試過表彰,所有你需要的是逃跑的斜線,即
echo $exa | sed 's/-/\//g'
,但選擇不同的分隔符是更好的。
的tr
工具可能是在這種情況下比sed
一個更好的選擇:
x=tmp/variable/custom-sqr-sample/test/example
echo "$x" | tr -- -/
(該--
並非絕對必要,但誤以爲-
一個選項保持tr
(和人類)。)
在bash
,你可以使用參數替代:
$ exa=tmp/variable/custom-sqr-sample/test/example
$ exa=${exa//-/\/}
$ echo $exa
tmp/variable/custom/sqr/sample/test/example
各色使用嘗試nt分隔符在你的'sed'命令中。我喜歡管道:'sed's | - |/| g''。 – squiguy 2013-03-07 18:23:17