2014-11-05 189 views
1

我需要shell腳本語句來替換"*"符號和字符串中的".*"。例如:string1="abc*def"轉換爲此string2:"abc.*def"。我與這段代碼嘗試,但它給出錯誤的輸出:替換字符串中的字符

IN="abc*def" 
chr=".*" 
arr=$(echo ${args[@]} | tr "*" "\n") 
for x in $arr 
do 
echo -n $x 
echo -n ".*" 
done 

for abc*def gives abc.*def.* not correct 
for abc*def* gives abc.*def.* correct 
for *abc*def* gives abc.*def.* not correct 

回答

0

您可以使用sed

p='*abc*def*' 
echo "$p" | sed 's/\*/.*/g' 
.*abc.*def.* 

確保您使用的是正確的引用,以避免外殼擴展*

+0

謝謝!它解決了我的問題 – BattleArray61 2014-11-05 06:14:35

+0

不客氣,很高興它解決了。 – anubhava 2014-11-05 06:14:59

0

嘗試此代碼 - >

a='abc*def' 
b=. 
c="${a/'*'/$b}"