简体   繁体   中英

Add header and trailer using awk

Below is my splitting files using awk, but I want to add header and trailer.

How can i do this?

awk -v DATE="$(date +"%d%m%Y")" -F\, 'BEGIN{OFS=","}NR==1 {h=$0; next} { gsub(/"/, "", $1); file="Assignment_"$1"_"DATE".csv"; print (a[file]++?"":h ORS) $0 > file}' Test_01012020.CSV

You need to print them in the BEGIN and END Section accordingly:

$ h=$'Fruit\tColor'
$ t=$'Total\tTotal'
$ cat file 
Mango Yellow
Lemon Green
$ awk -v h="$h" -v t="$t" 'BEGIN{FS=" ";OFS="\t";print h}{print $1,$2}END{print t}' file
Fruit   Color
Mango   Yellow
Lemon   Green
Total   Total

Alternativelly,
You can avoid the external variables and print header directly inside awk:

$ awk 'BEGIN{FS=" ";OFS="\t";print "Fruit","Color"}{print $1,$2}END{print "Total","Total"}' file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM