4

How can I copy files in a folder based on when the file was last edited? Lets say I want to copy all my files that I last edited today from c: to my folder bak. How can I achieve that?

I know that a regular copy command can be done like this:

cp source destination

eg.

cp *.c bak

Any suggestions?

Byte Commander
  • 110,243
John
  • 165

2 Answers2

7

Using find, the files (and only the files) modified in the last day are found by:

find . -type f -mtime 1 

so you can copy them with

find . -type f -mtime 1  -exec cp {} bak/ \; 

Meaning: find all entities under the current directory (.), of type "file" (-type f), modified at least 1 day from now (-mtime 1, but it's subtle, follow the link to learn more), and for each one of them execute the command cp followed by the name of the file that match the previous conditions and by a literal bak/ --- in the exec clause, the closing semicolon (escaped to avoid the shell eating it) closes the command and additionally means that the command is to be executed once for every match.

Notice that the directory tree will be flattened in the bak/ folder, so maybe using an archive format would be better.

For example, this is my script that makes a backup of all files in my working directories modified today and since two days in tar files and then move them to my Dropbox directory:

#! /bin/zsh 
#
cd $HOME
today="today-$(hostname)".tar
twodays="twodays-$(hostname)".tar
mydirs=(bin Documents Templates texmf Desktop) # list your top-level working dirs here  
rm -f $today $twodays
echo -n "Starting today and twodays backups... " 
find $mydirs -type f -mtime -1 -exec tar rf $today {} +
find $mydirs -type f -mtime -2 -exec tar rf $twodays {} +
echo "backups done:" 
ls -lh $today $twodays
echo "Moving to Dropbox" 
mv $today $twodays $HOME/Dropbox
sleep 2
dropbox status

it needs zsh because I'm lazy and didn't try to adapt to the array structure of bash, but surely someone here can do that (hint, hint)...

Rmano
  • 32,167
0

You can first specify which file that you modified last in your current folder with command

ls -lt

Or, you want to specify which file that you access last with command

ls -ltu

After that, you can copy the file with cp command. For copying multiple files, see this.

adadion
  • 358