Danny
Danny

Reputation: 65

Sorting a file by two columns while retaining the header on output files with AWK command

I want to sort a file with product and ID and I will get several files as output in awk. The command I'm using is

awk -F"|" 'NR>1 {print > "INITIATION_V1_"$1"_"$2".csv"}' test1.csv 

But it doesn't keep header for me in every output files I got. I searched a lot in google and tried with NR==1 || and NR==1 ; too but it doesn't work out for me. Anyone can help me in this problem? Thanks.

Upvotes: 1

Views: 53

Answers (1)

karakfa
karakfa

Reputation: 67507

awk -F\| 'NR==1 {h=$0; next} 
                {file="INITIATION_V1_"$1"_"$2".csv";  
                 print (a[file]++?"":h ORS) $0 > file}' test1.csv

a[file]++ is the line counter indexed by output filename, insert the header appended with ORS only before the first line, which will become the header for each split file.

Upvotes: 1

Related Questions