Monday, October 13, 2008

Generate xml from input file - bash script

Input file:

$ cat 21354.txt

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">
<lock fromTime="1223850098" toTime="1223850398">
<lock ip="" />
<lock fromTime="1223860353" toTime="1223860653">
<lock ip="" />
<lock fromTime="1223860184" toTime="1223860484">
<lock ip="" />

The bash script:

$ cat
#Generate xml from input file in a predefined format

[ -z $1 ] && echo " <filename>" && exit $NOFILE

basefile=$(basename $myfile .txt)

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

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


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

echo "Output xml is $basefile.xml"


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


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.

Jadu Saikia said...

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

Patrick Skelly said...

This script is great! It’s very close to what I need for a problem I am working on. I was hoping you might have some insight on tweaking it to my needs. I have a txt i am reading in but i cannot use spaces as the delimiter between the different parts of the file like your txt file. Is there a way I can specify parameters that say as each line is read, make from here to here part 1, from here to here part 2 and then insert those parts into the frame that is constructed?

© Jadu Saikia