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
4 comments:
Hey, good one..
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
@Mimi, would you mind giving more details on your question, would definitely help you.
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?
Post a Comment