1

I'm Trying to generate xml using awk as below.Input file:

10.112.232.34|bl|1
10.23.435.21|bl|1
34.4532.32.1|bl|0

and expected output should looks like

<Update version="1">
    <BlackListed_IP>
            <Added>
                    <value IP="180.104.243.1" CODE="BL"></value>
                    <value IP="180.104.243.1" CODE="BL"></value>
            </Added>
            <Deleted>
                    <value IP="180.104.243.1" CODE="BL"></value>
            </Deleted>
    </BlackListed_IP>

Below is what i'm using to get expected output.

function prepere_xml{
while IFS='' read -r line || [[ -n "$line" ]];
do
    while IFS='|' read f1 f2 f3
       if [ "$f3" == 1 ]; then
           awk -v c="$line" -F\| 'BEGIN{printf "<Update version=\"%s\">\n        <BlackListed_IP>\n                <Added>\n", c} {printf "                        <value IP=\"%s\" CODE=\"%s\"></value>\n", $1, $2} END {printf "                </Added>\n        </BlackListed_IP>\n</Update>"}' $collect_sid_msg > Generated_Delta.xml
       else
           awk -v c="$line" -F\| 'BEGIN{printf "                <Deleted>\n", c} {printf "                        <value IP=\"%s\" CODE=\"%s\"></value>\n", $1, $2} END {printf "                </Deleted>\n</Update>"}' $collect_sid_msg >> Generated_Delta.xml
       fi
    done<$input_file
done < $update_version
}

where update_version.txt file has

1
1

1 Answer 1

2
$ cat tst.awk
BEGIN { FS="[|]" }
$3 == 1 { addedIp[++numAdded]=$1; addedCode[numAdded]=$2; next }
{ deletedIp[++numDeleted]=$1; deletedCode[numDeleted]=$2 }
END {
    printf "<Update version=\"%d\">\n", update_version
    print  "    <Blacklisted_IP>"
    print  "        <Added>"
    for (i=1; i<=numAdded; i++) {
        printf  "            <value> IP=\"%s\" CODE=\"%s\"></value>\n", addedIp[i], toupper(addedCode[i])
    }
    print  "        </Added>"
    print  "        <Deleted>"
    for (i=1; i<=numDeleted; i++) {
        printf  "            <value> IP=\"%s\" CODE=\"%s\"></value>\n", deletedIp[i], toupper(deletedCode[i])
    }
    print  "        </Deleted>"
    print  "    </Blacklisted_IP>"
}

$ awk -v update_version=1 -f tst.awk file
<Update version="1">
    <Blacklisted_IP>
        <Added>
            <value> IP="10.112.232.34" CODE="BL"></value>
            <value> IP="10.23.435.21" CODE="BL"></value>
        </Added>
        <Deleted>
            <value> IP="34.4532.32.1" CODE="BL"></value>
        </Deleted>
    </Blacklisted_IP>
Sign up to request clarification or add additional context in comments.

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.