2016-11-11 196 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。