Using find - Deleting all files/directories (in Linux ) except any one Using find - Deleting all files/directories (in Linux ) except any one shell shell

Using find - Deleting all files/directories (in Linux ) except any one


find can be a very good friend:

$ lsa/  b/  c/$ find * -maxdepth 0 -name 'b' -prune -o -exec rm -rf '{}' ';'$ lsb/$ 

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 '{}' ';': call rm -rf for everything else

By the way, another, possibly simpler, way would be to move or rename your favourite directory so that it is not in the way:

$ lsa/  b/  c/$ mv b .b$ lsa/  c/$ rm -rf *$ mv .b b$ lsb/


Short answer

ls | grep -v "z.txt" | xargs rm

Details:

The thought process for the above command is :

  • List all files (ls)
  • Ignore one file named "z.txt" (grep -v "z.txt")
  • Delete the listed files other than z.txt (xargs rm)

Example

Create 5 files as shown below:

echo "a.txt b.txt c.txt d.txt z.txt" | xargs touch

List all files except z.txt

ls|grep -v "z.txt"a.txtb.txtc.txtd.txt

We can now delete(rm) the listed files by using the xargs utility :

ls|grep -v "z.txt"|xargs rm


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/shif [[ -z $1 ]]; then    files=`ls -l`else    files=`ls -l | grep -v $1`fi;for file in $files; do    rm -rvi $filedone;