简体   繁体   English

外壳脚本sed替换

[英]shell script sed replace

I have this file config.xml 我有这个文件config.xml

<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="dev@callback.apache.org" href="http://cordova.io">
    Apache Cordova Team
</author>
 <enter>PASSWORD</enter>
<content src="index.html" />
<access origin="*" />

I tried to do it with sed without success. 我试图用sed来做,但没有成功。

I need to do this: 我需要这样做:

$./script.sh config.xml NEWPASSWORD

to get: 要得到:

<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="dev@callback.apache.org" href="http://cordova.io">
    Apache Cordova Team
</author>
 <enter>NEWPASSWORD</enter>
<content src="index.html" />
<access origin="*" />

Using backreference: 使用反向引用:

sed "s/^\( *<enter>\)\([^>]*\)</\1$2</" "$1"
  • ^\\( *<enter>\\) : search for lines starting with any number of spaces followed by <enter> . ^\\( *<enter>\\) :搜索以任意数量的空格开头,后跟<enter> Matching characters are captured with escaped parentheses. 匹配的字符用转义括号捕获。

  • \\([^>]*\\)< : following characters up top next < are captured in a second group. \\([^>]*\\)< :在第二个组中捕获了在上一个<下一个字符。

  • \\1$2< : in the substitution string, characters from first group are output( \\1 ) followed by the second parameter value passed to the script, ( $2 , the new password value) \\1$2< :在替换字符串中,输出第一组中的字符( \\1 ),然后输出第二个参数值( $2 ,新密码值)

The command is applied to $1 , the file passed as first parameter to the script (the file name). 该命令将应用于$1 ,该文件作为第一个参数传递到脚本(文件名)。

To edit the file in place, use the -i flag: 要在适当位置编辑文件,请使用-i标志:

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

The good result is: 好的结果是:

$cat script.sh

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

Then: 然后:

$./script.sh config.xml NEWPASSWORD

Many thanks to everyone, especially to Kenavoz. 非常感谢大家,尤其是Kenavoz。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM