Append header with awk

I have to append the header (ie "START OF LINE") to a file only if there is data in it.
Below command is showing header though there is no data in a file, can you suggest how to correct..

awk '{NR!=0} BEGIN{print "START OF LINE"}; {print}' file

Why not

awk 'NR == 1 {print "START OF LINE"} 1' file

?

EDIT: or

[ -s "$FILE" ] && { echo "START OF LINE"; cat "$FILE"; }
1 Like

RudiC already told you how to do it but you might profit from understanding why your code did not work:

The reason why this doesn't work is that "NR" is only updated when records are read. Otherwise awk would have to read the whole file to determine how many records there are in it before it even begins to process it, no?

The BEGIN-part of awk is executed (aas the name implies) before any part of the input file is read and therefore "NR", at the time when this is executed, is always 0.

I hope this helps.

bakunin

2 Likes

Hello JSKBOS,

Following may also help you on same.

awk '{printf("%s%s\n",FNR==1?"START OF LINE":"",$0)'   Input_file

Thanks,
R. Singh

1 Like