shell - parsing a list file (awk/bash) -
what i'm going creating csv file out of parsed list.
[input.txt] list of gadgets. version: 11 created by: jayfour 1 toy no ordered 2 box no ordered 3 spade yes in_stock 4 nail yes in_stock 5 chair no ordered 6 table yes in_stock 7 apple no ordered 9 phone yes in_stock # generated 2014
now created script, should 'awk' , create me csv file this:
[output.csv] | id | item | status | stock | | 3 | spade | yes | in_stock | | 4 | nail | yes | in_stock | | 6 | table | yes | in_stock | | 9 | phone | yes | in_stock |
"|" represents table borders.
script:
#!/bin/bash ifiles=`ls input.txt` ifile in $ifiles echo "id;item;status;stock\r" > output.csv id=`awk '/yes/' $ifiles | awk {'print $1'}` itm=`awk '/yes/' $ifiles | awk {'print $2'}` stat=`awk '/yes/' $ifiles | awk {'print $3'}` stck=`awk '/yes/' $ifiles | awk {'print $4'}` echo "$id;$itm;$stat;$stck\r" >> output.csv done
as can imagine, did not work way. got issues breaks within csv (maybe caused faulty read-in/parsing input-file line line.
well - how fix? :)
this achieve wish:
cat input.txt | awk 'begin { print "id;item;status;stock" }; /yes/ { printf "%s;%s;%s;%s\n", $1,$2,$3,$4 }'
to placed inside loop of course.
explanation: start printing header (begin block) each line whith yes, print each field separated ';'
there's more elegant way in awk, less easy understand @ first.
i.e: cat input.txt | awk 'begin { ofs=";"; print "id","item","status","stock" }; /yes/ { print $1,$2,$3,$4 }'
here let awk manage output giving him output field separator (ofs) within begin block;
output is:
id;item;status;stock 3;spade;yes;in_stock 4;nail;yes;in_stock 6;table;yes;in_stock 9;phone;yes;in_stock
edit completeness: bash become:
#!/bin/bash ifiles=`ls input.txt` echo "id;item;status;stock\r" > output.csv ifile in $ifiles cat $ifile | awk 'begin { ofs=";"}; /yes/ { print $1,$2,$3,$4 }' >> output.csv done
as may not want repeat header, done before loop , not anymore in awk part.
Comments
Post a Comment