bash 脚本根据文件名中的日期查找旧文件
我正在开发一个 bash 脚本,该脚本需要根据一个变量搜索单个目录中“旧”的文件,该变量指定在超过阈值之前需要经过多少天,并且文件被标记为要执行操作(可以是任何内容)从移动到存档到删除,等等...)。
问题是文件的修改时间与确定文件需要多久才能采取行动无关,因为文件可能很少更改,脚本的执行时间可能会有所不同,等等
......确定保存的文件是 YYYY-MM-DD 形式的实际文件名(或带有日期命令的 %F)。以文件名contents-2011-05-23.txt为例。可以在此目录中运行哪些命令来查找超过一定天数的所有文件(我当前将阈值设置为 7 天,可以更改)并打印出它们的文件名?
I'm developing a bash script that needs to search out files within a single directory that are "old" based off a variable that specifies how many days need to pass before the threshold is exceeded and the files are marked for action (could be anything from move to archive to delete, etc...).
The catch is that the modify time of the file is irrelevant in determining how old the files need to be before taken action upon, as the files may infrequently be changed, the execution time of the script can vary, etc...
The time that determines hold the files are is in the actual file name in the form of YYYY-MM-DD (or %F with the date command). take for instance the filename contents-2011-05-23.txt. What command(s) could be run in this directory to find all files that exceed a certain amount of days (I have the threshold currently set to 7 days, could change) and print out their file names?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
创建一个 bash 脚本 isOld.sh,如下所示:
然后通过运行以下命令向上述文件授予执行权限:
最后从目录顶部运行此 find 命令以打印超过 7 天的文件,如下所示:
Create a bash script isOld.sh like this:
Then give execute permission to above file by running:
And finally run this find command from top of your directory to print files older than 7 days as:
在BSD中,
-j
用于防止设置日期,-f
参数用于设置输入日期的格式。 :首先,您需要找到自 1970 年 1 月 1 日以来的天数:
现在,您可以使用它来找出 7 天前的时间:
数字 604800 是 7 天的秒数。
现在,对于目录中的每个文件,您需要找到字符串的日期部分。我不知道有更好的方法。 (也许有人知道一些 Bash 魔法)。
一旦我们有了文件日期,我们就可以使用 date 命令来确定该日期(以秒为单位)是否小于(因此早于截止日期)。
在 Linux 中,您可以使用
-d
参数来定义必须采用YYYY-MM-DD
格式的日期:现在,您可以使用它并找到秒数:
其他所有内容应该或多或少与上面相同。
In BSD, the
-j
is used to prevent the date being set and the-f
parameter is used to set the format of the input date. :First, you need to find today's date in the number of days since January 1, 1970:
Now, you can use that to find out the time seven days ago:
The number 604800 is the number of seconds in seven days.
Now, for each file in your directory, you need to find the date part of the string. I don't know of a better way. (Maybe someone knows some Bash magic).
Once we have the file date, we can use the date command to figure out if that date in seconds in less than (and thus older than the cutoff date)
In Linux, you use the
-d
parameter to define the date which must be inYYYY-MM-DD
format:Now, you can take that and find the number of seconds:
Everything else should be more or less the same as above.
如果您每天运行该命令,您可以这样做:
当然可以添加其他通配符
If you run the command daily, you could do this:
Additional wildcards could be added ofcourse
这是我最长的内衬之一:-)这里再次包装:
That's one of my longest one liners :-) Here it is again wrapped: