Need to split date time into two separate field using awk

Viewed 392

I have the following awk command and output to convert a DAT file into CSV with specific FS but I would like the fields that contain date time value split into two separate fields plus add :00 seconds in time format.

awk command:

awk 'BEGIN{FS="\024"; OFS = ","; ORS = "\n"} {gsub(/\376/, "\"", $0); print $1, $2, $3, $4, $5}' input.dat > output.csv

input

þNUMþþDATE CREATEDþþDATE SENTþþDATE MODIFIEDþþDATE RECEIVEDþ þNUM00000001þþþþ9/11/2017 12:00 AMþþ6/16/2018 12:00 AMþþþ þNUM00000002þþþþ5/2/2016 12:00 AMþþ6/16/2018 12:00 AMþþþ

output:

"NUM","DATE CREATED","DATE SENT","DATE MODIFIED","DATE RECEIVED" "NUM00000001","","9/11/2017 12:00 AM","6/16/2018 12:00 AM","" "NUM00000002","","5/2/2016 12:00 AM","6/16/2018 12:00 AM",""

desired output:

"NUM","DATE CREATED","CREATED TIME","DATE SENT","SENT TIME","DATE MODIFIED","MOD TIME","DATE RECEIVED","RECEIVED TIME" "NUM00000001","","","9/11/2017","12:00:00 AM","6/16/2018","12:00:00 AM","","" "NUM00000002","","","5/2/2016","12:00:00 AM","6/16/2018","12:00:00 AM","",""

Is there a code I can add per field to perform the split? Note that some lines/rows can be NULL for date/time.

1 Answers

Based on sample data, The datestime need to be split by the first space into date and time. You can use awk functions. For example:

awk '
  # Get Date
function get_d (v) {
  sep = index(v, " ")
  return substr(v, 1, sep-1) "\"" ;
}
   # Get Time
function get_t (v) {
  sep = index(v, " ")
  if ( !sep ) return ""
  # insert :00 to time.
  tt= substr(v, sep+1, 5) ":00" substr(v, sep+6)
  # Remove leading zero from hour.
  sub("^0", "", tt)
  return "\"" substr(v, sep+1, 5) ":00" substr(v, sep+6)
#  return "\"" substr(v, sep+1, 99) ;

}

BEGIN {FS="\024"; OFS = ","; ORS = "\n"}
{gsub(/\376/, "\"", $0);
  print $1, get_d($9), get_t($9), get_d($10), get_t($10), get_d($11), get_t($11), get_d($12), get_t($12)}
' input.dat > output.csv
Related