csv 如何仅显示符合所设置要求的数据?

cgfeq70w  于 2023-01-28  发布在  其他
关注(0)|答案(3)|浏览(135)

我有一个程序,在一个csv文件,其中存储的数据在这种格式'姓氏,名称,YYYYMMDD'(最后一位是年月日为生日),只接受只有公历年,我希望我的程序显示所有文件,对应于输入的月份(字符串的名称的月份)。
例如,如果输入月份是“May”,我的程序应该显示所有在生日的MM部分有05的文件。
有人能解释一下我该怎么做吗?

#!/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
lbsnaicq

lbsnaicq1#

对于 GNUdate(1)和grep(1),类似于:

#!/usr/bin/env bash

read -rp "[Enter csv file]: " file
read -rp "[Enter month]: " month

[[ -z "$file" || -z "$month" ]] && {
  printf >&2 'file and month needs an input value!\n'
  exit 1
}

[[ -e "$file" ]] || {
  printf >&2 "Cannot open \`%s' (No such file or directory)\n" "$file"
  exit 1
}

##: Add more test if needed such as if the file is
##: A regular file and not a directory and so on...
##: readable by the user and so on...
##: See help test

input_month="$(date -d "1$month" '+%m' 2>&1)" || {
  stat=$?
  printf >&2 '%s\n' "${input_month/1}"
  exit "$stat"
}

grep "$input_month" "$file" || exit
  • 参见help test
jv2fixgn

jv2fixgn2#

似乎是awk的理想工作

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

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

月。awk为:

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; }
gmxoilav

gmxoilav3#

使用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 [[ "$mm" == *"$month"* ]] ; then
        printf "%s\n" "$line"
    fi
done <"$target_csv"

脚本的另一个版本显示monthtarget_csv的位置参数和/或默认值的使用:

#!/bin/bash

# You may pass the target month as positional parameter 
# to script execution or will default to the value May and
# You may pass the target csv file as the second positional 
# parameter or will default to the value my.dat.
# Example usage:  ./script_name May target.csv
month="${1:-May}"
target_csv="${2:-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 [[ "$mm" == *"$month"* ]] ; then
        printf "%s\n" "$line"
    fi
done <"$target_csv"

相关问题