如何编写脚本根据上次修改日期将文件从一个目录复制到另一个目录?
ls -al
-rw-r--r-- 1 用户 用户 100 2011-05-二十六12:33ABC1234_封面_10344000_2011-05.doc
我到底想要做的是,使用上面 ls -al 的粗体部分结果ABC1234_frontcover_10344000_2011-05.doc
将文件复制到/home/abcd/ABC1234/2011-05/26/
。
date -r $file +%m
应该有某种方法可以使用和的值来实现basename *.doc | awk -F_ '{print $1}'
。帮帮我,怎么做?
答案1
我刚刚花了一些时间尝试这一点并得出了以下脚本:
#!/bin/bash
# set folder where files are located
SOURCE_FOLDER=/path/to/source
# define folder to which the files have to be copied
TARGET_FOLDER=/home/abcd
# ####
cd "${SOURCE_FOLDER}"
for FILE in *; do
# everything which is not a normal file
if [ ! -f "${FILE}" ]; then
echo "Skipping non-file: '${FILE}'"
continue
fi
# extract data from file structure
FILE_DATE=$(date -r "$FILE" '+%Y-%m')
FILE_DAY=$(date -r "$FILE" '+%d')
FILE_PREFIX=${FILE%%_*}
# skip files which do not match the naming convention
if [ "${FILE_PREFIX}" = "" -o "${FILE_PREFIX}" = "${FILE}" ]; then
echo "Skipping file with wrong naming: '${FILE}'"
continue
fi
# create target folder
TARGET="${TARGET_FOLDER}/${FILE_PREFIX}/${FILE_DATE}/${FILE_DAY}"
echo "Copy '$FILE' to ${TARGET}"
mkdir -p "${TARGET}"
cp "$FILE" "$TARGET"
done
它还涵盖了一些特殊情况和概率检查。