2016-11-11 161 views
0

我有这个config.xml文件shell脚本SED替代

<widget id="com.example.hello" version="0.0.1"> 
<name>HelloWorld</name> 
<description> 
    A sample Apache Cordova application that responds to the deviceready event. 
</description> 
<author email="[email protected]" href="http://cordova.io"> 
    Apache Cordova Team 
</author> 
<enter>PASSWORD</enter> 
<content src="index.html" /> 
<access origin="*" /> 

我试图用sed来做到这一点没有成功。

我需要这样做:

$./script.sh config.xml NEWPASSWORD 

获得:

<widget id="com.example.hello" version="0.0.1"> 
<name>HelloWorld</name> 
<description> 
    A sample Apache Cordova application that responds to the deviceready event. 
</description> 
<author email="[email protected]" href="http://cordova.io"> 
    Apache Cordova Team 
</author> 
<enter>NEWPASSWORD</enter> 
<content src="index.html" /> 
<access origin="*" /> 

+0

谷歌中有很多例子,只是搜索文件中的sed替换字符串 –

回答

1

使用反向引用:

sed "s/^\(*<enter>\)\([^>]*\)</\1$2</" "$1" 
  • ^\(*<enter>\):搜索以任意数量的空格开头的行,然后搜索<enter>。匹配字符通过转义圆括号捕获。

  • \([^>]*\)<:在第二组中捕获以下字符最多的上一个<

  • \1$2<:在替换字符串,从第一组字符被输出(\1),然后传递给脚本第二参数值,($2,新密码值)

的命令是应用于$1,该文件作为第一个参数传递给脚本(文件名)。

编辑到位的文件,使用-i标志:

sed -i "s/^\(*<enter>\)\([^>]*\)</\1$2</" "$1" 
+0

这太棒了,它的工作!谢谢Kenavoz:PPP –

0

好结果是:

$cat script.sh 

#!/bin/sh 
file=$1 
sed -i "s/^\(*<enter>\)\([^>]*\)</\1$2</" "$1" 

然后:

$./script.sh config.xml NEWPASSWORD 

非常感谢大家,特别是到Kenavoz。