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?


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

# set folder where files are located

# define folder to which the files have to be copied

# ####
for FILE in *; do
    # everything which is not a normal file
    if [ ! -f "${FILE}" ]; then
        echo "Skipping non-file: '${FILE}'"

    # extract data from file structure
    FILE_DATE=$(date -r "$FILE" '+%Y-%m')
    FILE_DAY=$(date -r "$FILE" '+%d')

    # skip files which do not match the naming convention
    if [ "${FILE_PREFIX}" = "" -o "${FILE_PREFIX}" = "${FILE}" ]; then
        echo "Skipping file with wrong naming: '${FILE}'"

    # create target folder
    echo "Copy '$FILE' to ${TARGET}"
    mkdir -p "${TARGET}"
    cp "$FILE" "$TARGET"

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

  • +1 for not actually trying to parse the output of ls
    – Random832
    May 27 '11 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 '11 at 5:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.