so I'm using AWK in a project at work, to generate xml from csv. So far things are going relatively smoothly, but I have one thing I can't figure out.
For every field in each row, I must generate
<entry name=KWNamex>Field</entry>
Then I will need to pull data from a second file and generate
<entry name=KWValuex>Field</entry>
Disregarding the multi file input, which I haven't even began working on yet, how can I increment the value of "x" for each successive field in the record? Every time I try to use a variable, it pulls the value for that numbered field. For example, if I have PROJECT NUMBER in the first field, PROJECT NAME in the second, and USERID in the third, I want an output of:
This is probably the dumbest question ever, but I can't seem to use any variables without them providing the data inside that numbered field. Also, some rows won't have certain fields, so hardcoding the KW number for each column will not work (and would be a very sloppy solution anyway).
BEGIN {
print "<?xml version=\"1.0\" encoding=\"utf-8\">"
print "<Export>"
}
{
print "<section name=\"Query" NR "\">"
print "<entry name=\"DocumentType\">" $1 "</entry>"
for ( i = 2; i <= NF; i++ )
{
if ( $i )
print "<entry name=\"KWName1\">"$i"</entry>"
}
print "</section>"
}
END {
print "</Export>"
}
This is stored in
test.awk
, then I run:
awk -F, -f test.awk testfile.txt
testfile.txt is:
Document Type,Project Number,Org ID,Invoice Number
Invoices,Project Number,Org ID,Invoice Number
Requisitions,,,Invoice Number
Proposals,Project Number,Org ID,
Every time I set a variable to use as a counter for KWName, I end up calling the field that the counter relates to. So if I tried
x=1
and then increment x by 1 for every time I generate a KWName, I end up with something like
<entry name="KWNameInvoices">Invoices</entry>
I understand this is due to awk's use of variables to relate to fields. My question is whether I can use a variable as just a plain old variable within this awk statement, or if there's some other technique I can use to get the output I want. Thanks for the help!