this post was submitted on 31 Jan 2025
10 points (100.0% liked)
Linux Mint
1875 readers
16 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:
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
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
Yea that must be it! It's spitting out just the file name and not the whole path. There is only 1 level of depth, so I want to remove
so how do I get the whole path into xargs? I tried
xargs "$f"/
but fortunately that didn't work because it was trying to delete all the directories lmao XDHere's the command to delete the files:
for f in *; do find ./"$f" -type f | sort | tail -n 2 | xargs -n 1 rm; done
If you want to insure it will target the correct files, first run this command (I HIGHLY recommend you do this first. Verify BEFORE you delete so you don't lose data):
for f in *; do find ./"$f" -type f | sort | tail -n 2; done
I'll be adding another comment reply with a breakdown of the command shortly (just need to write it up)
Here's what's happening in the command;
for f in *; do
You already know this for loop, which is using the
*
glob to iterate over each directory in the current directory.find ./"$f" -type f
Instead of your original
ls
command, which gives the file names, and not their full paths, we're using GNUfind
, which outputs the full path of what it finds. The arguments are:./"$f"
- This tellsfind
where to start its search. I double qouted the$f
variable to properly expand the directory name even if it has nonstandard characters in it like spaces.-type f
- This tellsfind
what kind of file object to look for. So it's two parts.-type
to tellfind
there will be a specific type to look for, and thef
flag, which means file. Meaning, it will only find filesThe output of find is not sorted alaphabetically, so before piping the output to
tail
, we first pipe it tosort
, which by default will sort alphanumerically, which we then pipe totail
to grab just the last two files, and finally we get to thexargs
bit.Here I added the
-n 1
argument toxargs
to get it to work on the files one at a time. This isn't actually necessary. You could just run it asxargs rm
. I didn't realize that before I posted the command. (I'm still learning too! The learning never ends. :D )Thanks so much harsh!!! I will study this and hit Enter after I understand it.
Thanks again, that's epic.
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.