1

Okay, so I have this xml file. I need to replace every key value with a value from another file (txt). Both files are sorted so line 20 i.e inside the xml

<word key="ACTIVE" group="Service application" value="testvalue1"/>

Within my second file, on line 20 will be

testvalue2

I am looking for something which will change the value from testvalue1 to testvalue2

2 Answers 2

2

This should work.
We load the new values file, and then we process then xml file by replacing old value with new value using line number as the key.

awk 'FNR==NR{a[FNR]=$0;next}{$NF=gensub(/value=".*"\/>/,"value=\""a[FNR]"\"\/>","g",$NF);print}' file2 file
#OR working with regex groups:
awk 'FNR==NR{a[FNR]=$0;next}{$NF=gensub(/(value=")(.*)(".+)/,"\\1"a[FNR]"\\3","g",$NF);print}' file2 file

Testing:

$ cat file
<word key="ACTIVE" group="Service application" value="testvalue1"/>                                                                                                             
<word key="ACTIVE" group="Service application" value="testvalue2"/>                                                                                                             
<word key="ACTIVE" group="Service application" value="testvalue3"/>                                                                                                             
<word key="ACTIVE" group="Service application" value="testvalue4"/>
<word key="ACTIVE" group="Service application" value=""/>

$ cat file2
newvalue1
newvalue2
newvalue3
newvalue4                                                                                                                          
newvalue5

$ awk 'FNR==NR{a[FNR]=$0;next}{$NF=gensub(/value=".*"\/>/,"value=\""a[FNR]"\"\/>","g",$NF);print}' file2 file
<word key="ACTIVE" group="Service application" value="newvalue1"/>
<word key="ACTIVE" group="Service application" value="newvalue2"/>
<word key="ACTIVE" group="Service application" value="newvalue3"/>
<word key="ACTIVE" group="Service application" value="newvalue4"/>
<word key="ACTIVE" group="Service application" value="newvalue5"/>
1
  • @JamesBerrisford Updated with a better regex to carch even empty values of initial xml file. Commented Feb 20, 2017 at 11:42
0

A quick bash script:

#!/bin/bash
#set IFS to new line
IFS=$'\n';
line_number=0
for line in $(cat file1.xml); do        
    ((line_number++))
#get the value you want to replace
    value1=$(echo $line | grep -o -P 'value.{0,1000}' |  cut -d '"' -f 2)
#get the value you are replacing it with
    value2=$(sed "${line_number}q;d" file2.txt)
#run the replace using sed
    sed -i 's/'"${value1}"'/'"${value2}"'/g' file1.xml
done    

Note that this is untested, but it should work for your needs.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.