4

How can I write a script to copy files from one directory to another directory according to last modified date?

ls -al

-rw-r--r-- 1 user user 100 2011-05-26 12:33 ABC1234_frontcover_10344000_2011-05.doc

What exactly I want to do is, Using the above bold part of ls -al result the ABC1234_frontcover_10344000_2011-05.doc file should be copied to /home/abcd/ABC1234/2011-05/26/.

There should be some way to do it using value of date -r $file +%m and basename *.doc | awk -F_ '{print $1}'. Help me here, how?

1 Answer 1

7

I've just invested some time to try this and came up with the following script:

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

It also covers a couple of special cases and probability checks.

2
  • +1 for not actually trying to parse the output of ls
    – Random832
    May 27, 2011 at 0:53
  • Well, parsing ls output would be a bad idea as 'ls -l' prints different date format depending on locale and also depending on the timeframe when the last modification occurs (might show either day+month or just the year for older files). Maybe this answer helps others looking for some way to read file date too. Languages like Perl also offer functions to read such file properties too. It might be possible to use 'stat' too but then you would have to parse the output too.
    – SkyBeam
    May 27, 2011 at 5:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .