Mihai Marian Stoica Mihai Marian Stoica - 3 years ago 181
Bash Question

bash replace string in file with specific index

I have 2 files:

idfile.txt
:

1111
3333


replace.xml
:

<condition="online" id="1111" >
<condition="online" id="2222" >
<condition="online" id="3333" >
<condition="online" id="4444" >


I need a script to get below
output.xml
:

<condition="offline" id="1111" >
<condition="online" id="2222" >
<condition="offline" id="3333" >
<condition="online" id="4444" >


I use:

while read line; do
grep $line replace.xml | sed 's/condition="online"/condition="offline"/g' replace.xml >> output.xml
done < idfile.txt


My script replace all
condition="online"
in
condition="offline"
.

Thanks a lot!

Answer Source

Note, id attribute value from replace.xml should match any of the entries from idfile.txt to fit the condition.

Awk + paste solution:

awk -v ids="$(paste -s -d'|' idfile.txt)" 'match($2,ids){ sub("online","offline",$1) }1' replace.xml

The output:

<condition="offline" id="1111" >
<condition="online" id="2222" >
<condition="offline" id="3333" >
<condition="offline" id="4444" >
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download