1

I am attempting to copy files based on their modified date, as the file names do not include the date in them. Coincidentally, the files are the 22 newest files in the directory, so if I run the command ls -lt | head -22, the outputted files are exactly what I want to copy.

I had read this thread here, but the accepted answer didn't seem to work in Terminal, and it isn't exactly filtering by date, just by head.

I am running macOS Sierra 10.12.5.

peterh
  • 9,731
jau
  • 11

2 Answers2

3

The way to go for this kind of task, is to use :

find ./dir -mtime -10 -type f -exec cp {} ./another_dir/ \;

Replace -mtime -10 (last 10 days) by what you expect.

And PLEASE, don't parse ls output. Check http://mywiki.wooledge.org/ParsingLs

  • 1
    ls output parsing can be done correctly and securely, although it is mostly too much work. From the other way, calling different cp-s for every file is sub-optimal, too. – peterh Nov 10 '17 at 06:16
  • 1
    Another problem with your answer, that it copies the files changed in the last 10 days, and not the most recently changed 22 files. This is not exactly what the OP asked for, although I think similar problems could be solved more easily on your way. – peterh Nov 10 '17 at 06:22
-1
$ cp `ls -1t | head -22` /destination/dir
Ipor Sircer
  • 14,546
  • 1
  • 27
  • 39
  • 2
    NO. Don't parse ls output, you will have problems with space in filenames and the backquote backtick is used in the old-style command substitution, Check http://mywiki.wooledge.org/BashFAQ/082 – Gilles Quénot Oct 24 '17 at 15:20
  • @GillesQuenot See my comment to your answer. If we have reason to trust the input, and we want quick & simple solution, it can be a workable solution. – peterh Nov 10 '17 at 06:17
  • I think your answer would be okay, if 1) you should mention that it doesn't work always and it is obviously totally incompatible from any security/safety consideration 2) posting a single-line script without any comment is not a very HQ answer. | However, I think your solution could work in same scenarios (we can trust the directory and we know there are no spaces/specialchars in the files, AND we have only a few time). – peterh Nov 10 '17 at 06:20