4

How do you move files modified after a specific date (say 7 days for example) to another directory? I clumsily tried sending the output of

ls -t | head -n XX

But learnt recently that it isn't a good idea to parse ls.

Eweler
  • 143

1 Answers1

20

You are correct that it is best to avoid parsing ls. The solution below uses find. It will, by contrast, work with even the most difficult file names.

To move all files in the current directory modified less than 7 days ago to /destination/path, use:

find . -mindepth 1 -maxdepth 1 -mtime -7  -exec mv -t /destination/path {} +

How it works

  • find . -mindepth 1 -maxdepth 1

    This finds files belonging in the current directory (but not the current directory itself).

  • -mtime -7

    This tells find to select only files less than seven days old.

  • -exec mv -t /destination/path {} +

    This tells find to execute a mv command to move those files to /destination/path.

    This is efficient because find will replace {} + with many file names so that fewer mv processes need be created.

    Not all versions of mv support the -t option. GNU mv (Linux) does.

John1024
  • 74,655
  • Thanks for the breakdown, what do the braces at the end mean? Also, is it possible to specify timescales other than days for mtime? – Eweler Jun 05 '15 at 05:44
  • @Eweler find will substitute in file names where it sees the {}. In the form {} +, it will substitute in as many file names as fit on a command line. (If there are too many to fit, it will run another mv command with the remainder as needed.) – John1024 Jun 05 '15 at 05:51
  • can one explain what does the -t option in mv mean? – Walter Schrabmair Aug 08 '18 at 12:08
  • @WalterSchrabmair mv -t /destination/path file1 file2 tells mv to move files file1 and file2 to /destination/path. In other words, if -t path is specified, mv moves the files to path. (Not all versions of mv support this feature.) – John1024 Aug 08 '18 at 21:15