I have directory structure adc/asd/abc.20150918_150635.gz, adc/asd/abc.20150921_140748.gz .... (where .gz file names contain time stamps of its creation). Many other directories similar to asd are present here, eg. adc/gmf/abc.20150918_010738.gz, adc/ret/abc.20150921_140748.gz, all of them containing files with time stamps.

I want to copy latest modied file from all the directories (ie from asd,gmf,ret etc) with single command :).

I tried cp "adc/*/abc.* ." but it will copy all of the files. I want to copy only the latest modified file (with single command). Can any one help me?


To find the newest plain file (.) of each directory (/), a two pass method to first find the directories, then find the newest file (by mtime, or (om[1])) in each directory probably makes the most sense. With ZShell, this would look something like:

% typeset -a latest
% cd $TMPDIR
% mkdir latest
% cd latest/
% mkdir a b c 
% touch {a,b,c}/blah; sleep 3; touch {a,b,c}/a\ newer\ file
% for d in *(/N); do latest+=( $d/*(.om[1]) ); done
% [[ $#latest -eq 0 ]] && print uh oh
% print -l $latest
a/a newer file
b/a newer file
c/a newer file

So cp $latest destdir should then suffice (assuming that any files were found), unless for some unaccountable reason you've enabled the SH_WORD_SPLIT option in ZSH, in which case you'll need to deal with quoting issues as other shells do.

|improve this answer|||||
  • sorry I didnt get that... I am using k shell... how to write the program? – sagar alias jacky Sep 21 '15 at 16:38
  • pdksh looks somewhat less capable than ZSH, so would likely require find (perhaps unportable) or perhaps parsing ls output (ugh) or otherwise looping over each of the directory contents and then using stat to compare the mtime on files. – thrig Sep 21 '15 at 19:07
cp $(ls -1t */*/* | head -n 1) destdir

This is assuming the complete list of files fits into the available argument list space (or you'll get the "argument list too long" error).

ls -1t orders its arguments into order of modification time (newest first, the -t option) and shows one file per line (the -1 option). head -n 1 takes just the first line.

This is substituted into the command line so that you end up with cp newestfile destdir.

|improve this answer|||||
  • sorry.. it will not work for / . It will copy only one file from one directory. – sagar alias jacky Sep 21 '15 at 16:43
  • The question led me to believe that you wanted to copy just 1 file from all the directories. – wurtel Sep 22 '15 at 7:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.