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!

  • @ObsidianZed
    link
    11 day ago

    Just fyi, if you add a second question that you want people to see, you might avoid adding it as an edit and just post a new question instead or ideally include it all in the first post to begin with.

    Out of curiosity, what did you end up using for the first part? I know how I would have done it, but I’m self taught and always interested in learning new/different ways to do things.

    For the bonus EDIT question, are you moving all html files from any subdirectory under your current directory? If so, that’s much easier, but I would avoid putting your done folder under the scope that you’re scanning against as well as ensuring no files have matching names to avoid overwriting files already moved.

    All in all, I’m sure you can get there, but it does also help to have more information up front so we can provide clearer help.

    • @[email protected]OP
      link
      fedilink
      English
      121 hours ago

      Ok, thanks for the tip. I’m still getting used to Lemmy.

      I ended up using

      for f in *; do find ./“$f” -type f | sort | tail -n 2 | xargs -n 1 rm; done

      and it worked perfectly. For the bonus question, I’m moving the html files from 127 subfolders. They are the only content of the subfolders. I want to prepend an integer to each and copy them to a different folder, so instead of

      • folder1/file1
      • folder1/file2
      • folder2/file1
      • folder2/file2
      • folder2/file3

      I’ll have

      • 001file1
      • 002file2
      • 003file1
      • 004file2
      • 005file3