This is the contents of the directory I\'m working with:
misha@hp-laptop:~/work/c/5$ ls -l
total 8
-rw-rw-r-- 1 misha misha 219 May 20 15:37 demo.c
drwxrwxr
You can change your find
command to this:
find . -mindepth 1 -not -name demo.c -delete
-mindepth 1
ensure that you don't select DOT
-delete
will delete all files and directories it also displays this error message:
find: `./folder': No such file or directory
Why is that?
Because find
recognizes ./folder
as a directory when it first reads directory .
, before considering whether it matches the find
criteria or performing any action on it. It does not recognize that the action will remove that directory, so after performing the action, it attempts to descend into that directory to scan its contents. By the time it does that, however, the directory no longer exists.
There are multiple ways to address the problem. One not yet mentioned is to use the -prune
action. This tells find
not to descend into directories that match the tests:
find . ! \( -name demo.c -o -name . \) -exec rm -Rf {} \; -prune
That will serve nicely here, and it also has applications in areas where you are not deleting the directory and you do not want to limit the search depth.
Additionally, another way to avoid affecting .
would be to make use of the fact that find
accepts multiple base paths to test, that these can designate regular files if you wish, and that during pathname expansion any leading .
in a filename must be matched explicitly. If, as in your case, there are no dotfiles in the target directory (other than .
and ..
), then you can accomplish your objective like this:
find * ! -name demo.c -exec rm -Rf {} \; -prune
#before
ls -lrt
total 4
-rw-rw-r-- 1 user super 0 May 20 09:14 demo.c
drwxrwxr-x 2 user super 4096 May 20 09:14 folder/
-rw-rw-r-- 1 user super 0 May 20 09:14 test
#Command
ls -1 | grep -v demo.c |xargs rm -rf
#After
ls -lrt
total 0
-rw-rw-r-- 1 user super 0 May 20 09:14 demo.c