removing last created files
Hi,
I have been trying to figure this out. Suppose I have just created 10 files.Then when I do a ls -lrt I get the files in the order with the lastly created file name printed at the last. I understand till this. Suppose now I want to remove the lastly created n files. Is there a way to do this. Please help me with the command or the programming ( shell scripting) to do this. Also it will be very nice if you can provide me with some cool links regarding unix. I mean sites that can help me in studying and developing concepts regarding the operating system. Thanks and Regards Prasun |
Hi,
To answer the first question: tail and head will help you: ls -tr | tail -4 Will give you the last 4 files. Head does the same, but for the first files. man tail (head) for more details. Hope this helps. |
Thanks a lot, it will be really helpful.
Regards Prasun |
Important: don't forget -1 (that's a one, not an ell) as option to ls,
otherwise you might end up with several files on a line (which are all deleted). ls -rt1 If your files contain whitespaces, also include -Q (not sure if that helps). Edit: No, it doesn't seem to help. Does anyone have a solution? |
It's a rather lengthy command, but find can do it:
Code:
find . -maxdepth 1 -type f -newer $( ls -tr | tail -n 5 | head -n 1 ) -exec rm {} \; Code:
find . -maxdepth 1 -type f -newer $( ls -tr | tail -n 11 | head -n 1 ) -exec rm {} \; Standard disclaimer: Never, never, never execute any command responsible for moving or deleting files without verifying the command selects the files as you expect. Rip off the "-exec rm {} \;" portion to test until satisfied. |
I just found a solution myself:
ls -Q1rt | tail -4 | xargs rm By the way: I just deleted 3 GiB of videos because I forgot to cd into the test directory I created to find the solution :rolleyes: What do we learn from this? Exactly: never ever use rm without checking that you're in the right directory and entered the correct file names (especially when using wildcards or tab-completion followed by a fast ENTER ;) ). The same can happen with mv: mv file1 file2 some_dir Imagine you forget to type some_dir... |
Thanks to all of you ...it really proved to be of great help.
Regards Prasun |
alias?
Perhaps you shoudl alias rm to "rm -i"? Then call rm with full path when you really mean it!?
|
All times are GMT -5. The time now is 10:17 AM. |