Search code examples
bashfilemovedirectory

Move files to the correct folder in Bash


I have a few files with the format ReportsBackup-20140309-04-00 and I would like to send the files with same pattern to the files as the example to the 201403 file.

I can already create the files based on the filename; I would just like to move the files based on the name to their correct folder.

I use this to create the directories

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

Solution

  • Here’s how I’d do it. It’s a little verbose, but hopefully it’s clear what the program is doing:

    #!/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
    

    A few changes I’ve made to your original script:

    • I’m not trying to parse the output of ls. This is generally not a good idea. Parsing ls will make it difficult to get the individual files, which you need for copying them to their new directory.
    • I’ve simplified your if ... mkdir line: the -p flag is useful for “create this folder if it doesn’t exist, or carry on”.
    • I’ve slightly changed the slicing command which gets the year/month string from the filename.