If we want to delete all files and directories we use, rm -rf *
.
But what if i want all files and directories be deleted at a shot, except one particular file?
Is there any command for that? rm -rf *
gives the ease of deletion at one shot, but deletes even my favourite file/directory.
Thanks in advance
You can type it right in the command-line or use this keystroke in the script
P.S. I suggest
-i
switch forrm
to prevent delition of important data.P.P.S You can write the small script based on this solution and place it to the
/usr/bin
(e.g./usr/bin/rmf
). Now you can use it as and ordinary app:The script looks like (just a sketch):
If it's just one file, one simple way is to move that file to
/tmp
or something,rm -Rf
the directory and then move it back. You could alias this as a simple command.The other option is to do a
find
and thengrep
out what you don't want (using-v
or directly using one offind
s predicates) and thenrm
ing the remaining files.For a single file, I'd do the former. For anything more, I'd write something custom similar to what thkala said.
Short answer
Details:
The thought process for the above command is :
Example
Create 5 files as shown below:
List all files except z.txt
We can now delete(rm) the listed files by using the xargs utility :
I see a lot of longwinded means here, that work, but with a/ b/ c/ d/ e/
this removes everything except directory b/ and its contents (assuming your file is in b/. Then just cd b/ and
to remove everything else, but the file (named "filename") that you want to keep.
In bash you have the
!()
glob operator, which inverts the matched pattern. So to delete everything except the filemy_file_name.txt
, try this:See this article for more details: http://karper.wordpress.com/2010/11/17/deleting-all-files-in-a-directory-with-exceptions/
find
can be a very good friend:Explanation:
find * -maxdepth 0
: select everything selected by*
without descending into any directories-name 'b' -prune
: do not bother (-prune
) with anything that matches the condition-name 'b'
-o -exec rm -rf '{}' ';'
: callrm -rf
for everything elseBy the way, another, possibly simpler, way would be to move or rename your favourite directory so that it is not in the way: