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
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/*
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.
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.
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.
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/
Short answer
ls | grep -v "z.txt" | xargs rm
Details:
The thought process for the above command is :
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With