根据文件名称删除文件的脚本

根据文件名称删除文件的脚本

需要对我的脚本提出一些意见。我有一些类似以下格式的文件:-

-rw-r--r-- 1 root root 0 Apr 12 15:56 hostdata_mm-xxx1_2018_04_03.csv
-rw-r--r-- 1 root root 0 Apr 12 15:56 hostdata_mm-xxx1_2018_04_04.csv
-rw-r--r-- 1 root root 0 Apr 12 15:56 hostdata_mm-xxx1_2018_04_05.csv
-rw-r--r-- 1 root root 0 Apr 12 15:56 hostdata_mm-xxx1_2018_04_06.csv
-rw-r--r-- 1 root root 0 Apr 12 15:56 hostdata_mm-xxx1_2018_04_07.csv
-rw-r--r-- 1 root root 0 Apr 12 15:56 hostdata_mm-xxx1_2018_04_08.csv
-rw-r--r-- 1 root root 0 Apr 12 15:56 hostdata_mm-xxx1_2018_04_09.csv
-rw-r--r-- 1 root root 0 Apr 12 15:56 hostdata_mm-xxx1_2018_04_10.csv

我只需要一个文件,即昨天的数据,因此,我的脚本如下:-

#!/bin/bash

set -x
wd=/root/test
yest=$(date -d "yesterday" '+%Y_%m_%d')

cd $wd
for f in *[0-9][0-9][0-9][0-9]_[0-9][0-9]_[0-9][0-9].csv; do
date=${f#*}
date=${date%.csv}
date=`echo $date | rev`
date=${date:0:10}
date=`echo $date | rev`
(( $date < $yest )) && rm $f
done

但是我收到了这个错误

/usr/local/bin/testdelfile: line 15: ((: 2018_04_03: value too great for base (error token is "2018_04_03")
/usr/local/bin/testdelfile: line 15: ((: 2018_04_04: value too great for base (error token is "2018_04_04")
/usr/local/bin/testdelfile: line 15: ((: 2018_04_05: value too great for base (error token is "2018_04_05")
/usr/local/bin/testdelfile: line 15: ((: 2018_04_06: value too great for base (error token is "2018_04_06")
/usr/local/bin/testdelfile: line 15: ((: 2018_04_07: value too great for base (error token is "2018_04_07")
/usr/local/bin/testdelfile: line 15: ((: 2018_04_08: value too great for base (error token is "2018_04_08")
/usr/local/bin/testdelfile: line 15: ((: 2018_04_09: value too great for base (error token is "2018_04_09")
/usr/local/bin/testdelfile: line 15: ((: 2018_04_10: value too great for base (error token is "2018_04_10")

这是调试模式

+ for f in '*[0-9][0-9][0-9][0-9]_[0-9][0-9]_[0-9][0-9].csv'
+ date=hostdata_mm-xxx1_2018_04_10.csv
+ date=hostdata_mm-xxx1_2018_04_10
++ echo hostdata_mm-xxx1_2018_04_10
++ rev
+ date=01_40_8102_1kmc-ym_atadtsoh
+ date=01_40_8102
++ echo 01_40_8102
++ rev
+ date=2018_04_10
+ ((  2018_04_10 < 2018_04_12  ))
/usr/local/bin/testdelfile: line 15: ((: 2018_04_10: value too great for base (error token is "2018_04_10")

请指教

答案1

(( ... ))Bash 中的运算符需要算术值。2018_04_10是一个字符串,因此会出现错误。用于[[ ... ]]进行字符串比较。

但是对于日期,我建议将其转换为数字时间戳date +%s,以便与之进行比较(( ... ))

您可以更改脚本以使其具有:

yest=$(date -d "yesterday" '+%s')
for f in *[0-9][0-9][0-9][0-9]_[0-9][0-9]_[0-9][0-9].csv; do
   date=$(sed -r 's/.*([0-9]{4})_([0-9]{2})_([0-9]{2}).csv/\1-\2-\3/' <<< $f | xargs date +%s -d)
   (( $date < $yest )) && rm $f
done

答案2

脚本的问题在于字符串比较使用了不合适的运算符。只需将第 14 行中的替换(( ... ))[[ ... ]],脚本即可正常运行。

更多信息请访问http://tldp.org/LDP/abs/html/comparison-ops.html

我想提出一个更简单的解决方案。使用 find,您可以按名称排除要保留的文件,然后删除目录中的其他文件:

find . -not -name "hostdata_mm-xxx1_$(date -d 'yesterday' '+%Y_%m_%d').csv" -type f -exec rm {} ";"

相关内容