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

Linux Mint

1875 readers
19 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!



EDIT: Thanks for the awesome help guys! The next part of this is to move all the .html files into one folder (named "done"), prepending their name with an integer. So far I got:

n=1; for f in *; do find ./"$f" -type f | sort | xargs mv done/"$n$f"; n=$((n+1)); done

but that is... not really doing anything. The closest I have gotten so far is some error like

mv: Missing destination file operand

Any help is again appreciated!

you are viewing a single comment's thread
view the rest of the comments
[โ€“] skaarl@feddit.nl 1 points 4 hours ago (1 children)

Thanks so much harsh!!! I will study this and hit Enter after I understand it.

Thanks again, that's epic.

[โ€“] harsh3466@lemmy.ml 1 points 4 hours ago (1 children)

You're welcome! Happy I could help.

One other quick note, do the filenames or directories have spaces in them? If they do, that will cause a problem with the command as it is and need some additional modification. I accounted for the possible spaces in the directory names with the find command, but not with xargs. I just realized that as I was looking it over again.

[โ€“] skaarl@feddit.nl 1 points 26 minutes ago

That was it! Thank you. I got rid of over 150 files in 127 directories with a lot less clicks than through the file explorer.

Luckily this time there were no spaces in the names. Spaces in names are a PITA at my stage of learning, and I'm never sure if I should use ' or ".

Btw, new challenge in the edited original post, if you haven't yet exhausted your thinking quota for the day lol.