Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix Command to Delete all files in a directory but preserve the directory

Tags:

unix

I am looking for a unix command to delete all files within a directory without deleting the directory itself. (note the directory does not contain subdirectories).

like image 773
BIOS Avatar asked Jul 11 '12 09:07

BIOS


People also ask

How to delete all files in a directory in Linux?

To delete everything in a directory run: rm /path/to/dir/* To remove all sub-directories and files: rm -r /path/to/dir/* Let us see some examples of rm command to delete all files in a directory when using Linux operating systems. How to remove all the files in a directory?

How do I clear the contents of a file in Unix?

First, if you look at the rm command man page ( man rm under most Unix) you notice that –r means "remove the contents of directories recursively". So, doing rm -r . alone would delete everything in the current directory and everything bellow it. In rm –rf . the added -f means "ignore nonexistent files, never prompt".

How to remove all sub-directories of a file system?

If you want to remove not only the sub-directories and files of it, but also the directory itself, omit -mindepth 1. Do it without the -delete to get a list of the things that will be removed.

How do I force delete a file in Linux terminal?

To delete a specific file, you can use the command rm followed by the name of the file you want to delete (e.g. rm filename ). For example, you can delete the addresses. txt file under the home directory. How do you force delete a folder in Linux? Open the terminal application on Linux. The rmdir command removes empty directories only.


3 Answers

You can use find /path/to/your/folder/ -delete to delete everything within that folder.

While a wildcard rm would braek with too many files ("Argument list too long"), this works no matter how many files there are.

You can also make it delete only files but preserve any subdirectories:

find /path/to/your/folder/ -type f -delete

You could also specify any other criteria find supports to restrict the "results".

like image 171
ThiefMaster Avatar answered Oct 20 '22 02:10

ThiefMaster


try

rm -r yourDirectory/*

it deletes all file inside the "yourdirectory" directory

like image 40
Amxx Avatar answered Oct 20 '22 03:10

Amxx


rm -i <directory>/*

this should do the trick

EDIT: added -i just in case (safety first). directory should be a full or relative path (e.g. /tmp/foo or ../trash/stuffs)

like image 24
BigMike Avatar answered Oct 20 '22 01:10

BigMike