Tuesday, September 30, 2008

Linux - use find along with cp to copy specific files by date

The reason this came up is because someone I work with was trying to copy specific files from one folder to another, but only if they were created today. He tried using grep and didn't have any luck. I'm not saying you can't use grep, but I figured it out using find instead because it seemed to allow you to use more parameters. The trick is using the find command as your first argument in the cp command. Here's the example:

cp `find filename*.txt -mtime -1` /home/common/files

This will take any files from the current directory that are like filename.txt (e.g filename99.txt, filename130fff.txt, etc), AND that have been modified in the last 24 hours ( number x 24 hours. e.g. use 2 for 48 hrs, 3 for 72 hrs, etc.), and copy them to the directory /home/common/files. You could change mtime argument to mmin instead, and then the number following would be the number of minutes in the past the file would've been modified, which in this case would be 1 minute. In the find command, you can use a full file path as well so you don't have to start the command from within a particular folder. Hopefully that has enough information to at least get you started. To find more parameters for commands, use the man pages in Linux ("man find" or "man cp") to list them. You can always search Google too, which is what I usually do, and you may find some helpful examples. Here is the link to the page that pointed me in the right direction in regards to using find with date/time parameters: http://www.linux.ie/newusers/beginners-linux-guide/find.php

No comments: