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.
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 {} +
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.
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 anothermv
command with the remainder as needed.) – John1024 Jun 05 '15 at 05:51-t
option inmv
mean? – Walter Schrabmair Aug 08 '18 at 12:08mv -t /destination/path file1 file2
tellsmv
to move filesfile1
andfile2
to/destination/path
. In other words, if-t path
is specified,mv
moves the files topath
. (Not all versions ofmv
support this feature.) – John1024 Aug 08 '18 at 21:15