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 fi
mv subdir/preciousfile ./
rm -rf subdir
mkdir subdir
mv preciousfile subdir/
This looks tedious, but it is rather safe
rm -rf *
, its results depend on your current directory (which could be /
;-)*
: its expansion is limited by ARGV_MAX.At least in zsh
rm -rf ^filename
could be an option, if you only want to preserve one single file.
You can type it right in the command-line or use this keystroke in the script
files=`ls -l | grep -v "my_favorite_dir"`; for file in $files; do rm -rvf $file; done
P.S. I suggest -i
switch for rm
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:
rmf my_favorite_dir
The script looks like (just a sketch):
#!/bin/sh
if [[ -z $1 ]]; then
files=`ls -l`
else
files=`ls -l | grep -v $1`
fi;
for file in $files; do
rm -rvi $file
done;
you need to use regular expression for this. Write a regular expression which selects all other files except the one you need.
I see a lot of longwinded means here, that work, but with a/ b/ c/ d/ e/
rm -rf *.* !(b*)
this removes everything except directory b/ and its contents (assuming your file is in b/. Then just cd b/ and
rm -rf *.* !(filename)
to remove everything else, but the file (named "filename") that you want to keep.