2013-11-27 56 views
0

是否有一個perl/sed一行操作來處理shell腳本中的$ string,但不是文件操作?谷歌的結果顯示,perl的用戶只能用於文件操作。Perl正常字符串操作的一個班輪(不在文件!)

Forexample,我的shell腳本中,我使用

$mycurrent_path="/cygdrive/c/project_1/sources/" 
if[[ $1 == "/^project_\d$/i" ]] # For example I call this shell script with "Project_7" as the arg 
    perl -e -i 's/project_\d/$1/ $mycurrent_path` 
fi 
    echo $mycurrent_path 

這應該巧妙地打印: $ /cygdrive/C/project_7 /來源/

Perl是非常靈活,具有reg EXP但有些如何,通過上面的代碼的嘗試,perl不會作用於$ mycurrent_path變量,(也不知道如果reg表達式「if [[$ 1 ==」/^project_ \ d $/i「]]」像我在Perl中那樣工作的很好,讓我們假設這個條件檢查通過某種方式(通過用1強制進入)並進入。

回答

1
$mycurrent_path="/cygdrive/c/project_1/sources/" 

if[[ $1 == "/^project_\d$/i" ]] # For example I call this shell script with "Project_7" as the arg 
    mycurrent_path=`perl -pe "s/project_\d/$1/" <<<"$mycurrent_path"` 
fi 

echo "$mycurrent_path" 

即使受到if中的條件的保護,直接在任何腳本中都不是很好的練習場所shell變量($1)。使用bash參數擴展應該是更安全

$mycurrent_path="/cygdrive/c/project_1/sources/" 

if[[ $1 == "/^project_\d$/i" ]] # For example I call this shell script with "Project_7" as the arg 
    mycurrent_path="${mycurrent_path/project_?/$1}" 
fi 

echo "$mycurrent_path" 

或更安全的perl的版本:

$mycurrent_path="/cygdrive/c/project_1/sources/" 

if[[ $1 == "/^project_\d$/i" ]] # For example I call this shell script with "Project_7" as the arg 
    mycurrent_path=`perl -pe 'BEGIN{$s=shift}s/project_\d/$s/' "$1" <<<"$mycurrent_path"` 
fi 

echo "$mycurrent_path" 
+0

是這個工程現在),非常感謝 –

0

爲什麼沒有perl的使用bash?像(未經測試)

mycurrent_path=${mycurrent_path//project_[0-9]/$1} 

東西或許你還需要「禁用了javascript -s nocasematch」 ......