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!

  • huf [he/him]@hexbear.net
    link
    fedilink
    English
    arrow-up
    1
    ·
    5 hours 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.

    • skaarl@feddit.nlOP
      link
      fedilink
      English
      arrow-up
      1
      ·
      44 minutes ago

      Can find be used with tail?

      Thank you for the tips, but now I’m getting “Cannot remove: No such file or directory” all the way down! The files are there, I see them, they come up in the terminal, but for some reason xargs rm does not want to delete them. When I put the -f flag, rm doesn’t give an error but the files are still there! wtf

      • huf [he/him]@hexbear.net
        link
        fedilink
        English
        arrow-up
        1
        ·
        37 minutes ago

        find can be used with tail, but if you’re doing nul-delimited stuff (-print0, -0), then you’ll want tail to run in nul-delimited mode too (-z apparently).

        or you can say “fuck files with newlines in them, i aint supporting that shit”, and then you just need the “” to still support filenames with spaces.