1

I have an XML file that has a set of entries like this:

<attr name="trajectory" value="nodo2"/>

What I want to do is to substitute the value field in each entry of the file by an entry of the form "nodoX", where X should be read from a second file that contains a list of numbers, e.g "file2" contains:

4
8
67
52

In that case my processed XML file should have substituted the previous entries by:

<attr name="trajectory" value="nodo4"/>
...
<attr name="trajectory" value="nodo8"/>
...
<attr name="trajectory" value="nodo67"/>
...
<attr name="trajectory" value="nodo52"/>
...

Currently I am trying with the following awk command but it is not working:

awk '/"trajectory"/ {if (getline < "file2") {x=$1; sub(/"nodo2"/,"\"nodo"x"\"")}}1' $XML_INPUT_FILE > $XML_OUTPUT_FILE

Could someone advise the correct way to get this done in awk ?

Thanks

Daniel

0

4 Answers 4

2

getline < "file2" overwrites $0, so the sub command will not do what you want. Try:

awk '/"trajectory"/ {if (getline x < "file2") {sub(/"nodo2"/,"\"nodo"x"\"")}}1' 

See http://www.gnu.org/software/gawk/manual/gawk.html#Getline

Sign up to request clarification or add additional context in comments.

Comments

1

Well, you can do that with awk...

awk 'BEGIN { c=1 ; while ((getline line < "OTHER_NUMBERS") > 0) { a[c]=line ; c++ } }
     NR == 1 { c=1 }
     /<attr name="trajectory" value="nodo[0-9]+".>/ {
          print gensub("^(.*=.nodo)[0-9]+(.*)","\\1" a[c] "\\2","g",$0)
          c++
     }
     ! /<attr name="trajectory" value="nodo[0-9]+".>/ { print }' XMLFILE

Generally it reads your number files into an indexed array, then on every (matching) trajectory lines prints the replacement. Note that it can fail you, if the number of lines in the numbers file is less than the number of nodo lines...

Comments

0

This might work for you:

 awk 'FNR==NR{n[++i]=$1;next};/"trajectory"/{sub(/[0-9]+/,n[++j],$3)}1' file2 XML

Comments

0

solution below

awk '
BEGIN{i = 0; while(getline num < "file2"){a[i] = num;i++}}
/"trajectory"/{sub(/nodo2/,"node"a[NR-1], $0);print $0}' file1

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.