by Random_BSD_Geek · 11y ago · 0 comments
Here's a random example: Prune a a scratch directory of files older than one week.
find /dir -type f -mtime +7 -delete
How would you do it without find? (Serious question. I know it can be done with other tools but since I can do it in one line with find I've never bothered to look for another solution.)
With python you can do something like
[os.unlink(file) for file in [os.path.join(*path_parts) for l in [list(zip(repeat(root),files)) for root,dirname,files in os.walk('/tmp') if len(files) != 0] for path_parts in l] if datetime.fromtimestamp(os.stat(file).st_mtime) < datetime.now() - timedelta(days=7)]
...I suspect there might be bit more elegant solutions too cutoff_date = datetime.now() - timedelta(days=7)
for basepath,_,files in os.walk('/tmp'):
for filename in files:
filepath = os.path.join(basepath, filename)
if datetime.fromtimestamp(os.stat(filepath).st_mtime) < cutoff_date:
os.unlink(filepath)
Python is not really that great when forced to oneliner format, and I'm not really a good code golfer anyways. ls /dir -re | ? LastWriteTime -lt (Get-Date).AddDays(-7) | del
i.e.1: enumerate the files recursively (ls is alias for Get-ChildItem)
2: pipe through a filter (? is alias for Where-Object) that selects only files written to more than 7 days ago
3: pipe those files to the Remove-Item command (del is alias for Remove-Item)