嘿,伙计们,我一直在解决这个问题,我有一个CSV文件我必须根据用户的输入来过滤特定的月份。记录格式
firstName,lastName,YYYYMMDD
但问题是输入是字符串而文件中的月份是数字
例如
> 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
online:
MONTH=March; REGEX=`date -d "1 ${MONTH} 2022" +%m..$`; grep $REGEX guest.csv
Awk可以很容易地将月份名称转换为数字和进行过滤。
awk -v month="March" -F , '
BEGIN { split("January February March April May June July August September October November December", mon, " ");
for(i=1; i<=12; i++) mm[i] = mon[i] }
mm[0 + substr($3, 5, 2)] == month' guest.csv
BEGIN
块建立了一对关联数组,可以在主脚本中使用它们根据名称查找月份。修改-v month="April"
以搜索不同的月份
如果您想将其封装在shell脚本中,您可以轻松地将参数解析为变量:
#!/bin/sh
monthname=$1
shift
awk -v month="$monthname" -F , '
BEGIN { split("January February March April May June July August September October November December", mon, " ");
for(i=1; i<=12; i++) mm[i] = mon[i] }
mm[0 + substr($3, 5, 2)] == month' "$@"