I am trying to filter records based on date field format "YYYYMMDD" through awk command . Source & Target file is comma separated with Header

Viewed 91
awk 'BEGIN {FS = ","};(NR>=2){($2 > "20210331");}' test1.csv > test.csv

File test1.csv:

Col1,Col2,Col3
A,20210101,JohnA
B,20210101,JohnB
G,20210501,JohnG
C,20210108,JohnC
D,20210202,JohnD
E,20210331,JohnE
F,20210401,JohnF
H,20210715,JohnH

Expected output:

Col1,Col2,Col3
G,20210501,JohnG
F,20210401,JohnF
H,20210715,JohnH
2 Answers

You can simply treat the dates in your shown samples like integers and compare them. In order to print the header, you need a separate condition.

awk 'BEGIN{FS=OFS=","} FNR==1{print;next} 20210331<$2' Input_file

I prefer the shorter code below:

awk 'BEGIN{FS = OFS = ","}(FNR == 1) || ($2 > 20210331)' test1.csv
Related