0

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!

2
  • I can't figure out what you want Commented Sep 28, 2017 at 12:46
  • 4
    11111 is not equal to 1111 ! Commented Sep 28, 2017 at 12:49

3 Answers 3

1

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" >
Sign up to request clarification or add additional context in comments.

Comments

0

If your files are going to be large, I would use awk. Please note that your idfile.txt should be:

1111
3333

To get something interesting.

This is how I would do it with awk:

#!/bin/bash

awk '
  BEGIN {
    while( (getline $l < "idfile.txt") > 0 ) {
      if( $l ~ /^.+$/ ) {
        id[$l] = 1;
      }
    }
    close("idfile.txt");
  }

  /^.+$/ {
    split($2, a, "\"");
    if( id[ a[2] ] ) {
      printf "<condition=\"online\" id=\"%s\">\n", a[2];
    }
    else {
      printf "<condition=\"offline\" id=\"%s\">\n", a[2];
    }
  }
' replace.xml >output.xml

The BEGIN block reads the id file to the id array. awk uses a hash to implement lookups so they are efficient. The regular expressions /^.+$/ are meant to avoid processing empty lines. The code is meant to be contained in a bash (text) file.

$2 will get the pieces id="nnnn"> and the split will get in array a[2] the part of that within the quotes.

Comments

0

awk one liner

$ awk 'FNR==NR{a[$0]; next} ($4 in a){gsub(/online/,"offline")}1' idfile.txt FS='"' replace.xml

First : Store all id's in a
Next, while iterating over replace.xml, if id i.e $4 exists in array a then replace online with offline. Note: Field separator is " for replace.xml

Output

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.