2013-11-27 34 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” ......