Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

file

linux

shell

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

like image 669
RajSanpui Avatar asked Apr 14 '11 06:04

RajSanpui


People also ask

How do you delete all files in a directory without deleting the directory?

Open the terminal application. To delete everything in a directory run: rm /path/to/dir/* To remove all sub-directories and files: rm -r /path/to/dir/*

How do I select all files except one?

Click the first file or folder you want to select. Hold down the Shift key, select the last file or folder, and then let go of the Shift key. Hold down the Ctrl key and click any other file(s) or folder(s) you would like to add to those already selected.

How do I delete all files except a specific file extension?

Highlight all the files you want to keep by clicking the first file type, hold down the Shift key, and click the last file. Once all the files you want to keep are highlighted, on the Home Tab, click Invert Selection to select all other files and folders.

How do I delete multiple directories in Linux?

To remove multiple directories at once, use the rm -r command followed by the directory names separated by space. Same as with files, you can also use a wildcard ( * ) and regular expansions to match multiple directories.


2 Answers

find can be a very good friend:

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

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:

$ ls
a/  b/  c/
$ mv b .b
$ ls
a/  c/
$ rm -rf *
$ mv .b b
$ ls
b/
like image 85
thkala Avatar answered Nov 05 '22 17:11

thkala


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.txt
b.txt
c.txt
d.txt

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

ls|grep -v "z.txt"|xargs rm
like image 28
Thyag Avatar answered Nov 05 '22 16:11

Thyag