this post was submitted on 31 Jan 2025
6 points (100.0% liked)

Linux Mint

1875 readers
9 users here now

Linux Mint is a free Linux-based operating system designed for use on desktop and laptop computers.

Want to see the latest news from the blog? Set the Firefox homepage to:

linuxmint.com/start/

where is a current or past release. Here's an example using release 21.1 'Vera':

https://linuxmint.com/start/vera/

founded 3 years ago
MODERATORS
 

As the title says, I just started with linux mint and am falling in love with bash scripts ๐Ÿ˜ Actually I'm not sure if it's considered a script, but I want to delete the last 2 files in all subfolders in a folder. So far I've (after great effort) got the terminal to list the files, but I want to delete them. Here is how I get them listed:

for f in *; do ls $f | tail -n 2; done

All their names come satisfyingly up in the terminal. Now what? I tried adding | xargs rm but that didn't delete them. I also tried something with find command but that didn't work either. Some folders have 3 items, so I want to delete #2 and 3. Some folders have 15 items so I want to delete #14 and 15. Folders are arranged by name, so it's always the last 2 that I want to delete.

It's frustrating to be sooooo clooooose, but also very fun. Any help is appreciated!

top 4 comments
sorted by: hot top controversial new old
[โ€“] clmbmb@lemmy.dbzer0.com 1 points 3 hours ago (1 children)
[โ€“] skaarl@feddit.nl 1 points 2 hours ago (2 children)

for f in *; do ls $f | tail -n 2 | xargs rm -rf; done

You mean like that? rm -rf followed by a question mark does not inspire confidence XD

[โ€“] huf@hexbear.net 1 points 1 hour ago

this will break pretty badly if you have filenames with spaces or newlines in them. so to make this actually robust, you now get to learn about find -print0, xargs -0, and why you always, always need to add "" around variables in bash.

[โ€“] clmbmb@lemmy.dbzer0.com 1 points 2 hours ago

yes. that's what I suggested.. the question mark was there to ask you if you tried that :-D I'm at work, pretty busy :-D I hope you read the rm manual.

-r means recursive
-f means force, which will delete the files/directories without interaction