LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   bash sort files by date in file name (https://www.linuxquestions.org/questions/programming-9/bash-sort-files-by-date-in-file-name-443623/)

thedude2010 05-10-2006 07:13 PM

bash sort files by date in file name
 
I have a bash script that does daily backups of a public html folders

there is a backup directory with files inside labeled "Wed May 10 20:14:36 EDT 2006-domain.tgz" and so on.
I want to have 5 daily backups and on the 6th remove the first one.

I'm fairly new to bash scripting and can't quite to seem to figure out how to sort by the date in the file names in order to delete the earliest one.

I would appreciate any help

Thanks
Tom

twantrd 05-10-2006 07:43 PM

Hi,

So, you want to delete the oldest file on the 6th time it makes a tarball right? Simple enough:

[root@linux mnt]# ls -alrt
total 20
-rw-r--r-- 1 root root 0 Mar 3 2004 file1
-rw-r--r-- 1 root root 0 Apr 3 2004 file2
-rw-r--r-- 1 root root 0 May 3 2004 file3
-rw-r--r-- 1 root root 0 Jun 3 2004 file4
-rw-r--r-- 1 root root 0 Jul 3 2004 file5
drwxr-xr-x 2 root root 4096 Nov 19 2004 floppy
drwxr-xr-x 2 root root 4096 Nov 19 2004 cdrom
drwxr-xr-x 22 root root 4096 Mar 8 10:07 ..
drwxr-xr-x 2 root root 4096 Apr 17 12:23 test
-rw-r--r-- 1 root root 0 May 10 16:21 file6
drwxr-xr-x 5 root root 4096 May 10 16:22 .

The files I made are "file[123456]" as you can see and I changed the time to reflect which one is older than the other. Once file6 is created, you can just run this to delete file1 (which is the oldest file)

Code:

rm -f `ls -alrt | head -2 | grep -v total | awk '{print $9}'`
Of course, you can make this a bit more prettier and have check conditions and whatnot. This is just a head start for you :). Let us know if you still need more help in creating your bash script.

-twantrd

thedude2010 05-10-2006 07:55 PM

Let me give that a shot. Thanks

chrism01 05-10-2006 08:50 PM

FYI, some bash cmds don't handle filenames with spaces in them properly, without extra fooling around. I highly recommend you use underscores or somesuch instead.
Also,
ls -1|sort
will sort the files by name, regardless of timestamp if you want that, otherwise use
ls -1t
sorts by date stamp

muha 05-12-2006 03:49 AM

nice article on (possibly automatic) backup schedules (using rsync and cron):
http://spinink.net/2006/03/29/automa...-cron/#more-55

jim mcnamara 05-12-2006 10:02 AM

FWIW -
Code:

stat --format=%Y <filename>
gives the time (seconds since Epoch) the file was last modified.
This is a large number that sorts perfectly.

schneidz 05-12-2006 11:07 AM

you can try this:
http://www.linuxquestions.org/questi...highlight=time

my suggestion starts in post #10


All times are GMT -5. The time now is 06:46 PM.