Sla*_*ast 2 scripting date rename files
这是上下文:
在 samba 服务器上,我有一些文件夹(我们称之为 A,B,C,D ),它们应该从网络扫描仪接收文件。扫描仪呈现一个 PDF 文件,名称如下:
YYYYMMDDHHmmss.pdf
(年、月、日、时、分、秒)
我需要在这些 PDF 出现在文件夹中的那一刻或一分钟内重命名这些 PDF(我正在考虑 crontab)。
重命名必须是类似的东西
“[prefix_specific_to_the_folder]_YYYY-MM-DD.pdf”
我已经看到“date +%F”做了我想要的时间戳,我只需要在脚本中手动设置我的前缀。
我有算法,它必须是类似的东西
"-read file.pdf
-if the name of the file doesn't have [prefix]
-then mv file.pdf [prefix]_[date].pdf
-else nevermind about that file."
Run Code Online (Sandbox Code Playgroud)
我真的很难找到正确的语法。
我更愿意检索文件创建的系统时间戳并用它重命名文件,而不是使用扫描仪生成的文件名。
这是围绕该inotifywait实用程序构建的解决方案。(您也可以使用incron,但您仍然需要与此类似的代码。)在启动时运行它,例如从/etc/rc.local.
#!/bin/bash
#
cd /path/to/samba/folder
# Rename received files to this prefix and suffix
prefix="some_prefix"
suffix="pdf"
inotifywait --event close_write --format "%f" --monitor . |
while IFS= read -r file
do
# Seconds since the epoch
s=$(stat -c "%Y" "$file")
# Convert to YYYY-MM-DD
ymd="$(date --date "@$s" +'%Y-%m-%d')"
# Rename the file. Mind the assumed extension
mv -f "$file" "${prefix}_$ymd.$suffix"
done
Run Code Online (Sandbox Code Playgroud)
如果在同一天创建了两个或更多文件,我不确定您希望发生什么。目前,最近到达(并处理)的文件将替换同一日期的任何较早文件。