Menü schliessen
Created: January 11th 2012
Last updated: May 1st 2020
Categories: Linux
Author: Marcus Fleuti

Linux Bash :: Howto find and copy files recursively that were modified within a specific date range

Tags:  bash,  Linux,  recursive
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Problem description:

We needed to copy all files that were modified within the past 28 days from all subdirectories to another place whilst maintaining the whole directory structure. This cannot be done with a simple unix command thus we needed to develop a small script for this.

How it's done

The script accepts 3 parameters. Those are:

  1. The filename with the filepath which is delivered by 'find'
  2. The source directory
  3. The target directory

For the function to work you'll need to create a new file called copyfiles.sh and put the following code into it:

#!/bin/bash

# $1 = file
# $2 = source directory
# $3 = destination directory

FILE=`basename "$1"`
SRC_DIR=`dirname "$1"`
DEST_DIR=`echo "$SRC_DIR" | sed "s#$2#$3#"`

if ! [ -d "$DEST_DIR" ]; then
 mkdir -p "$DEST_DIR"
 echo "Verzeichnis erstellt: $DEST_DIR"
fi

cp -vfp "$1" "${DEST_DIR}/${FILE}"

Save and exit. Now you'll need to make that file executable:

chmod 755 copyfiles.sh

Now comes the real magic. Please modify the following command to your needs. The example below would do the following:

  1. Find all files in the directory /mnt/nas ...
  2. that have been modified within the past 30 days
  3. For all these files execute the copyfiles.sh script ...
  4. will will submit the relative filepath of all files found ( {} ), the source directory and the destination directory to the copyfiles.sh script.
find /path/to/sourceDIR -mtime -30 -exec ./copyfiles.sh '{}' '/path/to/sourceDIR' '/path/to/destinationDIR' \;