Sunday, February 20, 2022

[SOLVED] Using awk how to fetch the date day wise?

Issue

I'm stuck how to fetch the date in day wise i.e if date is like 03/12/2020 how can I fetch only "03" in awk? Let's make a scenario using dummy data, file records are given something as follows

Cust_id;  orderDate; orderAmt
101; 20/09/2020; 8000
102; 08/08/2020; 6000
103; 03/11/2020; 12000
104; 21-06-2020; 1200
105; 04-07-2020; 1300 

Possible Output:

103; 12000
105; 1300

how can I print the details of customer who bought item in very first week in any month using AWK? How to fetch the date field with day wise here. Also note that if record like 104 'id', if date format is changed i.e. 21-06-2020 from default 21/06/2020 how to deal it?

I have tried on stack overflow but didn't get this date situation problem and also tried below link couldn't help me more ?

https://www.unix.com/shell-programming-and-scripting/138974-using-awk-print-date.html


Solution

Adding one more variant here, could you please try following written and tested with shown samples. Pass date in DDMMYYYY format in awk's variable named dat with any dash or slashes and inside it will compare with 2nd field's substring(s) of it.

awk -v dat="04072020" '
BEGIN{
  FS="[[:space:]]*;[[:space:]]*"
  OFS="; "
}
dat == (substr($2,1,2) substr($2,4,2) substr($2,7,4)){
  print $1,$3
}
' Input_file

Explanation: Adding detailed explanation for above.

awk -v dat="04072020" '              ##Starting awk program from here and creating dat with date of DDMMYYYY format.
BEGIN{                               ##Starting BEGIN section of this program from here.
  FS="[[:space:]]*;[[:space:]]*"     ##Setting field separator spaces(one or more occurrences) semi colon and again one or more occurrences of spaces.
  OFS="; "                           ##Setting output field separator as semi colon space here.
}
dat == (substr($2,1,2) substr($2,4,2) substr($2,7,4)){ 
                                     ##Checking condition if dat is equal to substring of (1st,2nd)chars (4th,5th) and (7th,8th) chars collective sub string.
  print $1,$3                        ##Printing 1st and 3rd fields here.
}
' Input_file                         ##Mentioning Input_file name here. 


Answered By - RavinderSingh13
Answer Checked By - Robin (WPSolving Admin)