1

我的文件内容如下,所需的输出如下所示。使用单独的 sed 命令,我可以修改文件内容。说

sed -i -e 's!<tag1>FIELD1</tag1>!<tag1>Replaced contents of field1</tag1>! filename

但是我很难用单个 sed 脚本文件替换这些单独的命令。

This is a sample file containing a few tags

<tag1>FIELD1</tag1>
<tag2>FIELD2</tag2>

<tag1>FIELD1 Do not change me</tag1>
<tag2>FIELD2 Do not change me</tag2>

<tag1>FIELD1 Do not change me</tag1>
<tag2>FIELD2 Do not change me</tag2>

所需的输出是

This is a sample file containing a few tags

<tag1>Replaced contents of field1</tag1>
<tag2>Replaced contents of field2</tag2>
<tag2>Some addition to field2</tag2>

<tag1>FIELD1 Do not change me</tag1>
<tag2>FIELD2 Do not change me</tag2>

<tag1>FIELD1 Do not change me</tag1>
<tag2>FIELD2 Do not change me</tag2>

4

3 回答 3

3

您可以链接-e表达式。

例如:

sed -e 's!<tag1>FIELD1</tag1>!<tag1>Replaced contents of field1</tag1>!g' -e 's!<tag2>FIELD2</tag2>!<tag2>Replaced contents of field2</tag2>\n<tag2>Some addition to field2</tag2>!g' filename
于 2012-06-28T05:16:36.537 回答
1
tag=(  "tag1"          "tag2" )
find=( "FIELD1"        "FIELD2" )
repl=( "Replacement 1" "Replacement 2" )
regex=
I=$'\x01' # sed delimiter
for (( i=0; i<${#find[@]}; i++ )) ;do
    regex+="s$I<${tag[i]}>${find[i]}</${tag[i]}>$I<${tag[i]}>${repl[i]}</${tag[i]}>${I}g;"
done
sed "$regex" "$file"

您可能需要也可能不需要或需要g在每个表达式的末尾。

于 2012-06-28T05:51:04.820 回答
0

这对我有用。

sed_script 文件(一个文件)

/<tag1>FIELD1<\/tag1>/s!<tag1>FIELD1</tag1>!<tag1>Replaced contents of field1</tag1>!
/<tag2>FIELD2<\/tag2>/c\
<tag2\>Replaced contents of field2</tag2>\
<tag2\>Some addition to field2</tag2>

于 2012-06-29T00:31:36.187 回答