在Bash中将文件移动到正确的文件夹
我有一些格式为在Bash中将文件移动到正确的文件夹,bash,file,move,directory,Bash,File,Move,Directory,我有一些格式为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
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
你可以用find
find /path/to/files -name "*201403*" -exec mv {} /path/to/destination/ \;
我会这样做的。这有点冗长,但希望能清楚地知道程序在做什么:
#!/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将使获取单个文件变得困难,您需要这些文件将它们复制到新目录中ls
- 如果。。。mkdir行:
标志对于“如果此文件夹不存在,则创建此文件夹,或继续”非常有用-p
- 我稍微更改了从文件名中获取年/月字符串的切片命令