Removing all but X old directories on FreeBSD via Bash (no -printf, with spaces, without zsh)

There are several different topics in stackoverflow regarding finding / deleting the oldest directory / files in a directory. I read a lot of them and saw a lot of different ways that obviously work for some people on other systems, but not for me in my particular case.

Limitations:

The closest I got something like this (not complete):

find . -maxdepth 1 -d -name "Backup Set*" -print0 | xargs -0 stat -f "%m %N" | sort -r| awk 'NR>5' 

This gives me the directories that I want to delete, but now they have timestamps that I’m not sure that if I fail and go to rm, I will return to the situation where I cannot delete directories with spaces in them.

output:

 1450241540 ./Backup Set1 1450241538 ./Backup Set0 

Thanks for any help here.


Relevant posts I have looked at:

https://superuser.com/questions/552600/how-can-i-find-the-oldest-file-in-a-directory-tree

Bash scripting: deleting the oldest directory

Delete all but the most recent X files in bash

+5
source share
2 answers
 ... | awk 'NR>5' | while read -r timestamp filename; do rm -rf "${filename}"; done 

If read indicates more fields than variables, the remaining ones are simply concatenated into the last specified variable. In our case, we extract the timestamp and use everything else as it is for the file name. We iterate over the output and run rm for each entry.

I would recommend doing a test run with echo instead of rm so you can check the results first.


Alternatively, if you prefer xargs -0 version:

 ... | awk 'NR>5' | while read -r timestamp filename; do printf "%s\0" "${filename}"; done | xargs -0 rm -rf 

It also uses while read , but prints each file name with a zero byte delimiter, which can be accepted by xargs -0 .

+3
source

this cut cut -d ' ' -f 2- will display a timestamp

simple example

 echo '1450241538 ./Backup Set0'|cut -d ' ' -f 2- 

get rid of timestamps

the results will be

 ./Backup Set0 
0
source

Source: https://habr.com/ru/post/1238580/


All Articles