Converting a flat file in XML

Hello Friends,
I am new to UNIX shell scripting. Using bash....Could you please help me in converting a flat file into an XML style output file.

Flat file: (Input File entries looks like this)

John Miller: 617-569-7996:15 Bunting lane, staten Island, NY: 10/21/79: 60600

The output should look like this.

<STUDENTS>
<NAME>John Miller</NAME>
<ADDRESS>15 Bunting lane, staten Island, NY</ADDRESS>
<PHONE>617-569-7996</PHONE>
<BIRTHDATE>10/21/79</BIRTHDATE>
<SALARY>60600</SALARY>
</STUDENTS>

Hi welcome to the Unix forum. Is this homework? What have you tried so far?

Here is one way of doing it:

#!/bin/bash

trim()
{
    trimmed=${1}
    trimmed=${trimmed%% }
    trimmed=${trimmed## }

    echo ${trimmed}
}


IFS=":"

echo "<STUDENTS>"
while read name phone address birthdate salary
do
   echo "  <STUDENT>"
   echo "     <NAME>$(trim ${name})</NAME>"
   echo "     <ADDRESS>$(trim ${address})</ADDRESS>"
   echo "     <PHONE>$(trim ${phone})</PHONE>"
   echo "     <BIRTHDATE>$(trim ${birthdate})</BIRTHDATE>"
   echo "     <SALARY>$(trim ${salary})</SALARY>"
   echo "  </STUDENT>"
done < infile
echo "</STUDENTS>"

This produces the following output:

<STUDENTS>
  <STUDENT>
     <NAME>John Miller</NAME>
     <ADDRESS>15 Bunting lane, staten Island, NY</ADDRESS>
     <PHONE>617-569-7996</PHONE>
     <BIRTHDATE>10/21/79</BIRTHDATE>
     <SALARY>60600</SALARY>
  </STUDENT>
</STUDENTS>
1 Like

Here is another (without a trim):

xmltag(){
  printf "<%s>%s</%s>\n" "$1" "$2" "$1"
}

while IFS=: read name phone addr dob sal
do
  printf "<STUDENTS>\n"
  xmltag NAME      "$name"
  xmltag ADDRESS   "$addr"
  xmltag PHONE     "$phone"
  xmltag BIRTHDATE "$dob"
  xmltag SALARY    "$sal"
  printf "</STUDENTS>\n"
done <infile>outfile
2 Likes

Thanks I will give it shot!