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 ファイル (1 つのファイル)

/<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 に答える