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

时间:2017-04-01 02:29:28

标签: bash csv while-loop heredoc

我正在尝试将用户输入与此处的doc进行比较,以比较输入是否大于或小于2个数字(日期),如果是,则打印第一列。 我的文件看起来像这样:

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

用户可以输入20100215作为日期。这是我的while循环,使用while读取中包含的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循环会生成多个元素,如果有任何可能的解决方案。 谢谢, 基兰

1 个答案:

答案 0 :(得分:1)

您的问题仍然有点不清楚,我在这里阅读有些内容,但如果我猜对了,您想要循环CSV文件中的所有条目,如果$querystartend之间,您想要输出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"

示例使用/输出

使用您的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

如果我误解了你的意图,请告诉我一行,我很乐意进一步帮助。