Just started with linux mint, need help with a command
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
be careful using rm in a loop and/or with variable arguments, things can go very wrong :)
when i'm writing a complicated command line involving rm i often write and run it first with echo in place of rm just to be sure i am getting the results i expect. also when i re-run it actually using rm, i tend to use the -v option (which tells rm to print what it is doing) to reassure myself that i've just deleted what i wanted to and nothing else.
Additionally, for safety you can add the i flag to be promoted to confirm each removal. It may be tedious depending on the number of files, but it may also save you from deleting files and/or directories you don't want deleted.
For clarity, be careful with that -rf combo of flags. As another commenter mentioned, -r means recursive, which will delete directories and their contents. You're talking about deleting files. If you do not want directories and their contents removed, DO NOT use the -r flag.
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