Shell脚本从文件中获取日期部分,然后将其与过去2天进行比较

时间:2018-05-07 11:05:59

标签: bash shell

我有一个要求,我需要从文件名中提取日期部分,然后必须将该日期与过去2天进行比较,并且文件中的日期不应超过2天。

例如,我有一个文件名列表,如文件所示。

kuna_Project_10262017.txt
kuna_ProjectProfessional_10262017.txt
ffs_Programs_10_22_17_03_33.txt

我用

提取前两个的日期
row=($(awk -F '[_.]' '{print $3}' FFS_FILES.txt))

Row是一个包含日期部分的数组。

我正在尝试使用for循环来比较它。 但由于输入字符串的格式不是预期的格式,我无法将提取后的日期与前2个日期进行比较,并且从第三个文件名中获取日期也不奇怪。

有什么办法可以解决吗?

1 个答案:

答案 0 :(得分:0)

以下是带注释的示例脚本。

CompareSec=$((60*60*24*2));   #number of seconds in two days
now=$(date "+%s" -d 'now');      #current time in seconds since EPOCH

while read file ; do
 TimeStampRaw=$(echo "${file}" \
 | sed 's/\([A-Z,a-z]*_[A-Z,a-z]*_[0-9]*_[0-9]*_\)\([0-9][0-9].*\)/\120\2/' \
 | sed 's/[A-Z,a-z_.]//g' \
 | sed 's/\([0-9]\{2\}\)\([0-9]\{2\}\)\([0-9]\{4\}\)\(.*\)/\3\1\2 \4/')

 # sed 's/\([A-Z,a-z]*_[A-Z,a-z]*_[0-9]*_[0-9]*_\)\([0-9][0-9].*\)/\120\2/' 
 # adds 20 before short format of year ( 17 -> 2017, 18 -> 2018 ) in files named ffs_Programs_10_22_17_03_33.txt

 # sed 's/[A-Z,a-z_.]//g'
 # delete any letters, dots and lines from text, leaving only numbers

 # sed 's/\([0-9]\{2\}\)\([0-9]\{2\}\)\([0-9]\{4\}\)\(.*\)/\3\1\2 \4/'
 # puts Year at first, then month, day and optionaly time in format YYYYmmdd HHMM

 TimeStampSec=$(date +%s -d "${TimeStampRaw}")
 #file time in senconds since EPOCH

 TimeStampHum=$(date -d "${TimeStampRaw}")
 #file time in Human format

 if [ $((${TimeStampSec} + ${CompareSec})) -ge ${now} ] ; then 
      echo "${file} is newer than ${CompareSec} Sec. (${TimeStampHum})"
 else
      echo "${file} is older than ${CompareSec} Sec. (${TimeStampHum})"
 fi

done <1.txt

1.txt的内容:

$ cat 1.txt 
kuna_Project_10262017.txt
kuna_ProjectProfessional_10262017.txt
ffs_Programs_10_22_17_03_33.txt
teSt_fiLe_05_07_18_03_33.txt
teSt_fiLe_05072018.txt

输出是:

kuna_Project_10262017.txt is older than 172800 Sec. (Thu Oct 26 00:00:00 MSK 2017)
kuna_ProjectProfessional_10262017.txt is older than 172800 Sec. (Thu Oct 26 00:00:00 MSK 2017)
ffs_Programs_10_22_17_03_33.txt is older than 172800 Sec. (Sun Oct 22 03:33:00 MSK 2017)
teSt_fiLe_05_07_18_03_33.txt is newer than 172800 Sec. (Mon May  7 03:33:00 MSK 2018)
teSt_fiLe_05072018.txt is newer than 172800 Sec. (Mon May  7 00:00:00 MSK 2018)