3 ms·
find has a worse reputation than it deserves. Yes, its learning curve is steep; when I was learning Unix, find was one of the commands that really stymied me. B
by Random_BSD_Geek 11y ago
find has a worse reputation than it deserves. Yes, its learning curve is steep; when I was learning Unix, find was one of the commands that really stymied me. But like many powerful tools once you've learned it you can do some wonderful things with it.
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.)
- zokier 11y ago> 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
- monochromatic 11y agoWoof. That is one python program I would not call "executable pseudocode."
- zokier 11y agoMore idiomatic version is more readable but also more verbose: 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.
- useerup 11y agoIn PowerShell: 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)