Home > Mobile >  How can I only display data that conforms to the requirements put in place?
How can I only display data that conforms to the requirements put in place?

Time:01-26

I have a program that takes in a csv file which stores data in this format ` Lastname,Name,YYYYMMDD` (last bit is year month day for birthday) that only accepts **only gregorian calendar years** and I want my program to display all files which corresponds to the input month (string of the name of the month).

For instance, if the input month is "May", my program should display all files that have 05 in the MM section of the birthday.

Can anyone please help explain what should I ?

#!/bin/bash
    echo "Enter csv file"
    read file
    echo "Enter month"
    read month
    cat "$file" | cut -f3 -d',' |    // this line seperates the csv file and focuses on the 3rd argument, which are the birthdays

CodePudding user response:

Seems like an ideal job for awk

cat foo
Lastname,Name,20230523
foo,baz,20230117

m=May
awk -F, -vmonth=$m -f month.awk foo
Lastname,Name,20230523

month.awk is:

BEGIN {
    months["Jan"] = "01";
    months["Feb"] = "02";
    months["Mar"] = "03";
    months["Apr"] = "04";
    months["May"] = "05";
    code = months[month];
}

substr($3,5,2) ~ code {print $0; }

CodePudding user response:

Using BASH:

#!/bin/bash

month=May
target_csv=my.dat

while read -r line ; do 
    d="${line##*,}"
    case "${d:4:2}" in
        01) mm=Jan ;;
        02) mm=Feb ;;
        03) mm=Mar ;;
        04) mm=Apr ;;
        05) mm=May ;;
        06) mm=Jun ;;
        07) mm=Jul ;;
        08) mm=Aug ;;
        09) mm=Sep ;;
        10) mm=Oct ;;
        11) mm=Nov ;;
        12) mm=Dec ;;
        *) echo "unknown month" && exit 1 ;;
    esac

    if [[ "$month" == *"$mm"* ]] ; then
        printf "%s\n" "$line"
    fi
done <"$target_csv"
  • Related