将日期与 CSV 格式的日期范围进行比较 - BASH

Compare date to range of dates in CSV - BASH

我正在尝试将用户输入与此处的文档进行比较,以比较输入是大于还是小于 2 个数字(日期),如果是,我打印第一列。 我的文件如下所示:

Earth,19480210,19490228
Earth,19490229,19500216
Metal,19500217,19510205

用户可以输入 20100215 作为日期。这是我的 while 循环,它使用 while read

中包含的 2 个变量进行比较
while IFS=, read -r term start end; do
if [[ $query -ge $start && $query -le $end ]];then
    echo $term
fi
    echo $query
    exit
done << EOF
$(cat chzod)
EOF

输出如下所示:您的生肖是:水

火灾

地球

我不知道为什么while循环会产生多个元素,是否有任何可能的解决方案。 谢谢, 基兰

你的问题还是有点不清楚,我有点理解这里的字里行间,但如果我猜对了,你想遍历 CSV 文件中的所有条目,如果 $query介于startend之间,你要输出term。但是,如果在遍历整个文件后,如果没有匹配,您是否试图再次打印出查询?

如果是这样,那么你就是在循环逻辑上犯了错误。有很多方法可以处理这个问题,但是当执行多个查询时,您需要确认是否匹配,最简单的解决方案是简单地设置一个标志,在匹配时切换。然后在完成所有比较后,检查标志以查看是否已设置。

一个简单的例子是:

#!/bin/bash

fname="${1:-chzod}"    # take csv file as first argument (default: chzod)

printf "query: "       # prompt for query
read -r query

test -z query && exit  # validate query

declare -i matched=0   # declare matched flag, set to '0'

while IFS=, read -r term start end; do
    if [[ $query -ge $start && $query -le $end ]];then
        echo $term
        matched=1      # set 'matched' flag
    fi
done < "$fname"        # redirect CSV file into loop

# check 'matched' flag and if unset, output unmatched query
test "$matched" -eq '0' && echo "unmatched query: $query"

例子Use/Output

使用您的 CSV 文件,您会期望得到以下示例结果:

$ bash readearth.sh dat/earth.dat
query: 19490229
Earth

$ bash readearth.sh dat/earth.dat
query: 19510204
Metal

$ bash readearth.sh dat/earth.dat
query: 20100215
unmatched query: 20100215

如果我误解了你的意图,请给我留言,我很乐意进一步提供帮助。