-1

I am not bash expert. I need to write a script to copy latest (by date) file from one folder to another as following

from

/test/a/date1.bak
/test/a/date2.bak
/test/a/date3.bak 
/test/b/date1.bak
/test/b/date2.bak
/test/b/date3.bak

to

/test/a/sec/date1.bak
/test/b/sec/date1.bak

On the second step I need to delete oldest file by date in the destination directory

from

/test/a/sec/date1.bak
/test/a/sec/date2.bak
/test/b/sec/date1.bak
/test/b/sec/date2.bak

to

/test/a/sec/date1.bak
/test/b/sec/date1.bak
  • possible duplicate of Unix/Linux find and sort by date modified – l0b0 Jan 8 '14 at 15:57
  • 2
    Welcome to SU! We're not a script writing service. What have you got so far, and where exactly are you getting stuck? – Ƭᴇcʜιᴇ007 Jan 8 '14 at 15:58
  • I can copy and delete one by one cp $(ls -1t | head -1) /test/a/secure/ But I would like to do it in recursive way – user199857 Jan 8 '14 at 16:42
  • Please show us the actual date format you are using. Do you want to extract (parse) the date from the file name or do you want to use the file's modification time? – terdon Jan 8 '14 at 16:59
0

ok got it. Terdon I am need to use files modification date. Here what I did for the file copy:

for BDIR in ls -1 .; do TO_BACK=$(ls -t $BDIR | grep ".bak$" | head -1); if [ "$TO_BACK" ]; then echo "copy $BDIR/$TO_BACK to $BDIR/sec/$TO_BACK"; fi; done

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.