将文件移动到Bash中的正确文件夹

时间:2015-04-09 13:23:59

标签: 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 
    if [ ! -d ${old}/$i ]
    then
        mkdir ${old}/$i
    fi
done

2 个答案:

答案 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标记对于“创建此文件夹(如果该文件夹不存在)或继续”非常有用。
  • 我稍微更改了切片命令,该命令从文件名中获取年/月字符串。