Monday, October 13, 2008

Generate xml from input file - bash script


Input file:

$ cat 21354.txt
1223850098 192.168.31.4
1223860353 172.22.22.12
1223860184 172.17.3.45

Requirement: We need to generate an XML from the above input file, which should look something like the below:


$ cat 21354.xml
<mck version="2">
<ldb>
<lock fromTime="1223850098" toTime="1223850398">
<lock ip="192.168.31.4" />
<l_id="21354"/>
</lock>
<lock fromTime="1223860353" toTime="1223860653">
<lock ip="172.22.22.12" />
<l_id="21354"/>
</lock>
<lock fromTime="1223860184" toTime="1223860484">
<lock ip="172.17.3.45" />
<l_id="21354"/>
</lock>
</ldb>
</mck>


The bash script:


$ cat xmlgen.sh
#!/bin/sh
#Generate xml from input file in a predefined format
#

NOFILE=64
[ -z $1 ] && echo "xmlgen.sh <filename>" && exit $NOFILE

myfile=${1}
basefile=$(basename $myfile .txt)

#Construct the frame
header='<mck version="2">
<ldb>'

fmt=' <lock fromTime="%d" toTime="%d">
<lock ip="%s" />
<l_id="%s"/>
</lock>
'

footer='</ldb>
</mck>'

#Printing
{
printf "%s\n" "$header"
while read epoch ip
do
printf "$fmt" "$epoch" "$(( $epoch + 300 ))" "$ip" "$basefile"
done < "$myfile"
printf "%s\n" "$footer"
} > $basefile.xml

echo "Output xml is $basefile.xml"



Executing:

$ ./xmlgen.sh 21354.txt
Output xml is 21354.xml

3 comments:

GNUger said...

Hey, good one..

Meriem Beloucif said...

It is a good script, it helped me, I still have a question since I started using bash a week ago. In my .txt I have
tag :url ..path.../url
tag: blablabla /blablabla
I mean that I have a whole text like that and I want to reproduce the same file in XML but in the .txt I have also another tag which contains thousands of sentences that I want to enumerate in this way in the XML file :
tag : body
tag : sentence1 ...../sentence1
tag sentence n /sentence n

Could please help me.
Thanks
Mimi

Jadu Saikia said...

@Mimi, would you mind giving more details on your question, would definitely help you.

© Jadu Saikia www.UNIXCL.com