Home > database >  Filtering Month in CSV using Bash
Filtering Month in CSV using Bash

Time:05-09

Hey guys I have been working on this problem where I have got a CSV File where I have to filter specific months based on the input from the user. Record Format

firstName,lastName,YYYYMMDD

But the thing is the input is in String and the month in the file is in numbers.

For example

> cat guest.csv

Micheal,Scofield,20000312
Lincon,Burrows,19981009
Sara,Tancredi,20040923
Walter,White,20051024
Barney,Stinson,20041230
Ted,Mosbey,20031126
Eric,Forman,20070430
Jake,Peralta,20030808
Amy,Santiago,19990405
Colt,Bennett,19990906

> ./list.sh March guest.csv
Micheal,Scofield,20000312

CodePudding user response:

For filtering March you could do (in bash):

grep -E $'03.."?\r?$' guest.csv

remark: handles CRLF line endings and quoted dates

Now you just have to convert March to 03 in a case switch:

#!/bin/bash

case $1 in
March)
    month=03
;;
*)
    echo "error: unknown month: $1" 1>&2
    exit 1
;;
esac

grep -E "$month"$'.."?\r?$' guest.csv

CodePudding user response:

Oneliner:

MONTH=March; REGEX=`date -d "1 ${MONTH} 2022"  %m..$`; grep $REGEX guest.csv
  • Related