Command to delete half of files in directory.

Hello Friends,

I have directory called /tmp. which stores the log files.
Whenever it becomes full, i want to delete half of files from all log files.
even after deleting the files, if space is more than 90% then it should delete rest of half files.
While deleting files, older files should be deleted first.
Thanks in advance :slight_smile:

And where is the issue?

We see no attempts from you to write the script...

I am unable to find the logic to divide the files into half part. and delete the older files first. As i am not sure how much files are there in tmp directory, I am bit confused.

Why don't you try using find command to delete files of particular days/weeks old .. like all files older then 7 ...

then use unix "du / df " commands to checks if its usage = 90% .. if so delete all files else no nothing :wall:

If you provide a sample directory/number of files .. we would help you better :smiley:

Hello Nakul,

Here is the hint for you.

1- you can check the number of files by ls command with using wc command or by awk command.

2- you can then look for the man page for find command which have all the severa; options to search files older than specific number of days.

3- You can use exec command to delete those files within find command itself.

Could you please try the steps and let us know where you have stuck.

Thanks,
R. Singh

Thanks for reply.
Yes i can find out count of files by using

ls -lrt |wc -l

suppose it is 120
How can i delete the first 60 files then.?
File name is like

Server_stat_log.2013-11-10 

Will that format is helpfull to develop the logic.?

Experts Please help

find /your_directory -mtime +7 -exec rm -f {} \;

should help you to delete files.. you can simply use "cron" to execute the above command on particular day.

Plzzz How does the number of files matter in deletion :confused::eek:??

i suggest going by age of file would help you more ..

Try

ls -t1 >temp;split -nl/2 temp del;while read FN; do echo rm "$FN"; done <delab; rm temp dela?

and remove the echo when you're happy with the proposed deletions. Using xargs might reduce the number of rm calls but will not handle file names with spaces.