Ads

Check out value in brief website for more up-to-date content.

how to delete all old files ? but keeps only 3 latest files

in Python

%%python3

from pathlib import Path

D = Path('/home/abanoub/Work')

files = [(i, i.stat().st_mtime) for i in D.iterdir()

    if i.is_file()]

result = sorted(files, key = lambda w: w[1])[::-1][3:]

for file, day in result:

    file.unlink()


in Bash script. find command shows randomly, so we use ls -t.

%%bash

files = ($(ls -lt ~/Work))

len = ${#files[@]}

for ((i=3; i < $len; i++))

do

rm -f ~/Work/${files[$i]}

done

in Perl

perl -e'opendir$h,"/tmp";@f=sort{-M$a<=>-M$b}grep{-f}readdir$h;unlink@f[3..$#f]'

If you want to get new posts, make sure to subscribe to Value In Brief by Email.