首页 > 解决方案 > 我需要在 bash 中的用户输入上从一个日期读取文件名到另一个日期

问题描述

我需要你的帮助。我有一个脚本需要在用户输入日期读取从一个日期命名的文件到另一个日期。

目录中有很多名称中包含日期的文件,ej:

xxxx20200930.txt_001
xxxx20200930.txt_002
xxxx20201001.txt_001
xxxx20201001.txt_002
xxxx20201002.txt_001
xxxx20201002.txt_002

例如:

Indicate star date: 20200930
Indicate finish date: 20200202

我需要cat在所有文件之间,然后是grep(我已经解决了这一切)

我尝试过使用日期功能,但我总是遇到问题:

日期: fecha inválida «dateinput2» 日期: fecha inválida «dateinput»

startdate='dateinput'
enddate='dateinput2'


while [ ! "$(date -d ${dateinput})" ]; do
     read -p "Indicate a date please: " dateinput
done

While [ ! "$(date -d ${dateinput2})" ]; do
     read -p "Indicate a second date please: " dateinput2
done

enddate=$( date -d "$enddate" +%Y%m%d )   # rewrite in YYYYMMDD format
                                                  #  and take last iteration into account
thedate=$( date -d "$startdate" +%Y%m%d )
while [ "$thedate" != "$enddate" ]; do
    printf 'The date is "%s"\n' "$thedate"
    thedate=$( date -d "$thedate + 1 days" +%Y%m%d ) # increment by one day
done

这是我在这里找到的一些代码,但我无法让它工作

有谁能够帮我。

谢谢

标签: linuxbashdate

解决方案


使用我所拥有的,给定

$: printf "%s\n" *.txt*
xxxx20200930.txt_001
xxxx20200930.txt_002
xxxx20201001.txt_001
xxxx20201001.txt_002
xxxx20201002.txt_001
xxxx20201002.txt_002
xxxx20201003.txt_001
xxxx20201003.txt_002
xxxx20201004.txt_001
xxxx20201004.txt_002

我用这个:

start=20201001
end=20201003
started=0
ending=0
for f in *.txt*
do case "$f" in
   *"$start".txt*) started=1; echo "$f"; continue ;;
     *"$end".txt*) ending=1;  echo "$f"; continue ;;
   *) (( started )) ||                   continue;
      (( ending  )) &&                   continue;
      echo "$f"                                   ;;
   esac
done

输出 -

xxxx20201001.txt_001
xxxx20201001.txt_002
xxxx20201002.txt_001
xxxx20201002.txt_002
xxxx20201003.txt_001
xxxx20201003.txt_002

严重依赖短路逻辑。
文件名可能会破坏它。


推荐阅读