I would like to create a header for a file in the BEGIN
part of my awk script, but to do that I need to know how many fields there are. I could put a check within the main section to check if NR==1
but that will get evaluated on each row, slowing things down.
Below is my attempt using a one-liner.
fields.txt
a 1
b 2
c 3
Result:
awk 'NR==1{a=NF; print "before begin, there are ", a, "fields"}BEGIN{print "there are ", a, "fields"}{print a"\t"$0}END{print "there were", a, "fields"}' fields.txt
there are fields
before begin, there are 2 fields
2 a 1
2 b 2
2 c 3
there were 2 fields
I guess the BEGIN block still gets evaluated before the preceding block. Have I really accomplished my goal, or is the NR==1
check still getting evaluated on each line?
EDIT So just to put in perspective why I'm trying to do it the way I am
- I've got a file with say 100k rows and 40 columns
- This file is the output of another process in a pipeline, with the awk script being the last step
- I'm calculating two rows based on other rows and adding these to the output
- I want the final file to include a header that reflects the two new added columns