Friday, April 16, 2010

Linux: use awk to help generate XML file


We have a text file product_desc.txt like this:
   name product1
   size large
   weight 30lb
   price 10.00
   quantity 100
and we want to change it into XML format:
   <name>product1</name>
   <size>large</size>
   <weight>30lb</weight>
   <price>10.00</price>
   <quantity>100</quantity>
So we run command:

   awk '{print "<"$1">"$2"</"$1">"}' product_desc.txt

In the command, $1 refers to column 1 in file product_desc.txt, and $2 refers to column 2. The characters we want to output as is are put between quotes("").

The command will print the result on the screen. If you want to write it to a file, just use the redirection:

   awk '{print "<"$1">"$2"</"$1">"}' product_desc.txt >product_desc.xml

No comments:

 
Get This <