13
2
Possible Duplicate:
How to delete all files in a directory except some?
How to delete all but one(or some) file in Unix?
Something like
rm -rf -ignore myfile.txt *
13
2
Possible Duplicate:
How to delete all files in a directory except some?
How to delete all but one(or some) file in Unix?
Something like
rm -rf -ignore myfile.txt *
20
ls * | grep -v dont_delete_this_file | xargs rm -rf
Example :
mkdir test && cd test
touch test1
touch test2
touch test3
touch test4
touch test5
To remove all files except 'test2' :
ls * | grep -v test2 | xargs rm -rf
Then 'ls' output is :
test2
EDIT:
Thanks for the comment. If the directory contains some files with spaces :
mkdir test && cd test
touch "test 1"
touch "test 2"
touch "test 3"
touch "test 4"
touch "test 5"
You can use (with bash) :
rm !("test 1"|"test 4")
'ls' output :
test 1
test 4
8
Assuming you're using the bash shell (the most common case), you can use the negation globbing (pathname expansion) symbol:
rm -rf !(myfile.txt)
This uses extended globbing, so you would need to enable this first:
shopt -s extglob
1
cp myfile.txt somewhere_else;
rm -rf *
cp somewhere_else/myfile.txt .
1
ln myfile.txt .myfile.txt && rm -rf * && mv .myfile.txt myfile.txt
0
This page gives a variety of options depending on the shell: http://www.unix.com/unix-dummies-questions-answers/51400-how-remove-all-except-one-file.html
0
For a recursive rm
you'd need to do the recursion with find
and exclude the file(s) you wanted to keep (or grep
, but that can get you into whitespace trouble). For a shell glob, modern shells have glob patterns that can be used to exclude files; this can be combined with shell-level glob recursion when available (e.g. zsh
has rm **/*~foo/bar
— note that this is likely to run into argument length limits for large directory trees).
Was going to do very similar using find, but yours works and you were faster. +1 – Rory Alsop – 2011-03-30T18:06:03.173
2this fails if you have files with spaces in their names. – Mat – 2011-03-30T18:08:21.343
To handle filenames with spaces one could use
ls -1 | grep -v do_not_delete | xargs -I files rm "files"
– sebhofer – 2013-04-01T12:42:06.040