我有一些格式为ReportsBackup-20140309-04-00
的文件,我想将具有相同模式的文件发送到文件作为201403
文件的示例。
我已经可以根据文件名创建文件了;我只想根据名称将文件移动到正确的文件夹中。
我用它来创建目录
old="directory where are the files" &&
year_month=`ls ${old} | cut -c 15-20`&&
for i in ${year_month}; do
if [ ! -d ${old}/$i ]
then
mkdir ${old}/$i
fi
done
答案 0 :(得分:2)
你可以使用find
find /path/to/files -name "*201403*" -exec mv {} /path/to/destination/ \;
答案 1 :(得分:1)
我是这样做的。这有点冗长,但希望程序正在做的很清楚:
#!/bin/bash
SRCDIR=~/tmp
DSTDIR=~/backups
for bkfile in $SRCDIR/ReportsBackup*; do
# Get just the filename, and read the year/month variable
filename=$(basename $bkfile)
yearmonth=${filename:14:6}
# Create the folder for storing this year/month combination. The '-p' flag
# means that:
# 1) We create $DSTDIR if it doesn't already exist (this flag actually
# creates all intermediate directories).
# 2) If the folder already exists, continue silently.
mkdir -p $DSTDIR/$yearmonth
# Then we move the report backup to the directory. The '.' at the end of the
# mv command means that we keep the original filename
mv $bkfile $DSTDIR/$yearmonth/.
done
我对原始脚本进行了一些更改:
ls
的输出。这是generally not a good idea。解析ls将难以获得将其复制到新目录所需的单个文件。if ... mkdir
行:-p
标记对于“创建此文件夹(如果该文件夹不存在)或继续”非常有用。