How to copy files changed in last 20 days to a different location recusively

2 min read 26-10-2024
How to copy files changed in last 20 days to a different location recusively

In many scenarios, you may need to copy files from one directory to another based on their modification date. For example, you might want to back up files that have changed in the last 20 days to a different location. In this article, we’ll walk you through how to achieve this using command-line tools available on Unix-based systems, such as Linux and macOS.

Original Code Example

Here’s a straightforward example of the command you could use in a Unix-like environment:

find /path/to/source -type f -mtime -20 -exec cp {} /path/to/destination \;

Explanation of the Command

  1. find: This command is used to search for files in a directory hierarchy.
  2. /path/to/source: Replace this with the path of the directory you want to search.
  3. -type f: This option specifies that you are looking for files (not directories).
  4. -mtime -20: This option filters the results to only include files modified in the last 20 days. The - sign indicates "less than."
  5. -exec cp {} /path/to/destination ;: This part executes the cp command for each file found, copying it to the specified destination. Make sure to replace /path/to/destination with your desired path.

Practical Example

Let’s say you have a folder at /home/user/documents and you want to copy all files modified in the last 20 days to /home/user/backups. You would run the following command:

find /home/user/documents -type f -mtime -20 -exec cp {} /home/user/backups \;

Additional Explanation

Using the find command is powerful because it allows recursive searching through all subdirectories. By including the -exec option, you can execute any command on the files found, which makes this command extremely versatile.

Benefits of Using the Command

  • Efficiency: Instead of manually checking each file, this command automates the process.
  • Flexibility: You can modify the command to search for different timeframes or copy to various locations.
  • Scalability: This approach works for directories containing thousands of files without affecting performance.

Additional Considerations

  • Permissions: Ensure you have the necessary permissions to read from the source directory and write to the destination directory. You may need to use sudo if you encounter permission issues.
  • Dry Run: If you want to test the command without making any changes, you can replace -exec cp {} with -print to see which files would be copied:
find /home/user/documents -type f -mtime -20 -print

Useful Resources

By using the method outlined in this article, you can efficiently copy files modified in the last 20 days to a different location while leveraging the power of the Unix command line. This approach saves time and effort, making it a practical solution for file management in various scenarios. Happy file copying!