Linux delete all but one directory

Linux Delete All Files In Directory Using Command Line

Linux Delete All Files In Directory

The procedure to remove all files from a directory:

  1. Open the terminal application
  2. To delete everything in a directory run: rm /path/to/dir/*
  3. 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?

Suppose you have a directory called /home/vivek/data/. To list files type the ls command:
$ ls

Understanding rm command option that deleted all files in a directory

  • -r : Remove directories and their contents recursively.
  • -f : Force option. In other words, ignore nonexistent files and arguments, never prompt. Dangerous option. Be careful.
  • -v : Verbose option. Show what rm is doing on screen.

Deleting hidden vs non-hidden files

In Linux, any file or directory that starts with a dot character called a dot file. It is to be treated as hidden file. To see hidden files pass the -a to the ls command:
ls
ls -a
ls -la
To remove all files except hidden files in a directory use:
rm /path/to/dir/*
rm -rf /path/to/dir/*
rm *
In this example, delete all files including hidden files, run:
rm -rf /path/to/dir1/<*,.*>
rm -rfv /path/to/dir1/

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Bash remove all files from a directory including hidden files using the dotglob option

If the dotglob option set, bash includes filenames beginning with a ‘.’ in the results of pathname expansion. In other words, turn on this option to delete hidden files:

See GNU/bash man page for the shopt command online here:
man bash
help shopt

Linux Remove All Files In Directory

As I said earlier one can use the unlink command too. The syntax is:
unlink filename
For example, delete file named foo.txt in the current working directory, enter:
unlink foo.txt
It can only delete a single file at a time. You can not pass multiple files or use wildcards such as *. Therefore, I strongly recommend you use the rm command as discussed above.

Conclusion

In this quick tutorial, you learned how to remove or delete all the files in a directory using the rm command. Linux offers a few more options to find and delete files. Please see the following tutorials:

Читайте также:  Test drive unlimited вылетает при запуске windows 10

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Delete / Remove a Directory Linux Command

Commands to remove a directory in Linux

There are two command to delete a folder in Linux:

  1. rmdir command – Deletes the specified empty directories and folders in Linux.
  2. rm command – Delete the file including sub-directories. You can delete non-empty directories with rm command in Linux.

Let us see some examples and usage in details delete the directories.

rmdir command syntax to delete directory in Linux

The rmdir command remove the DIRECTORY(ies), if they are empty. The syntax is:
rmdir directory-name
rmdir [option] directory-name
Open the terminal application and run command to delete given directory. For example, delete a folder named dir1:
rmdir dir1

Delete directory Linux Command

Open a command line terminal (select Applications > Accessories > Terminal), and then type the following command to remove a directory called /tmp/docs:
rmdir /tmp/docs
If a directory is not empty you will get an error message that read as follows:
rmdir letters
Sample outputs:

You can cd to the directory to find out and list all files:
$ cd letters
$ ls
Delete those files or directories. In this next example, remove data, foo and bar if bar were empty, foo only contained bar and data only contained foo directories:
cd /home/nixcraft
rmdir -p data/foo/bar

Where,

  • -p : Each directory argument is treated as a pathname of which all components will be removed, if they are empty, starting with the last most component.

How to see a diagnostic message for every directory processed

Pass the -v option to the rmdir command:
$ rmdir -v dir1
Sample outputs:

Removing directories with rmdir and wildcards

We can use wildcards such as ‘*’ and ‘?’ to match and delete multiple directories. For example:
$ ls -l dir*
We have three dirs named dir1, dir2, and dir3. To delete all directories starting with ‘dir’ in the current, you would use the following command:
rmdir -v dir*

Linux remove entire directory including all files and sub-directories command

To remove all directories and subdirectories use the rm command. For example, remove *.doc files and all sub-directories and files inside letters directory, type the following command:

Warning : All files including subdirectories will be deleted permanently when executed the following commands.

$ rm -rf letters/
Sample session:

Where,

  • -r : Attempt to remove the file hierarchy rooted in each file argument i.e. recursively remove subdirectories and files from the specified directory.
  • -f : Attempt to remove the files without prompting for confirmation, regardless of the file’s permissions

Are you getting permission denied error message while removing directories?

Only owners can delete their directories. However, a sysadmin can delete any directories created by anyone on the system. The syntax is:
sudo rmdir /path/to/dir/
sudo rm -rf dir2
When prompted, you need to provide root user or sudo user password.

Use find command to delete unwanted directories

Say you want to find out all directories named ‘session’ and delete them in the current directory, run:
find . -type d -iname ‘session’ -delete

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

How to find and remove all empty directories

Run:
find . -type d -iname ‘session’ -empty -delete
Where,

  • -type d : Only search for directories and ignore all other files.
  • -iname ‘session’ : Search directory named ‘session’. You can use wildcards here too. For example, -iname ‘dir*’ .
  • -empty : Only match empty directories
  • -delete : Deletes all found empty directories only
Читайте также:  Установка windows как заработать

To delete all ‘.DS_store’ directories stored in /var/www/html, run:
sudo find /var/www/html/ -type d -name .DS_Store -exec rm <> \;
OR
sudo find /var/www/html/ -type d -name .DS_Store -exec rm <> +
The -exec option to the find command run an external command named rm to delete all files. The “ rm <> +/ ” is a better option as it uses one rm command to delete all .DS_Store directories.

Conclusion

This page showed how to delete a directory when it is empty. Further, it showed, how to remove folders using the rm and rmdir commands. See rm help page page for more info:

  • For more information read man pages: rm(1)

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

How do I remove a folder?

I am a new user and I am trying to remove a specific folder. I am using sudo rm /path/ , but it is not working. What is the correct command to use?

It is a file catolog I am attempting to remove but I am geting a message that it is empty.

6 Answers 6

Be sure the folder is really empty (hidden files/folders might be in there). Look at the file contents again with

If you’re absolutely certain that it doesn’t contain anything you want to have (including subdirectories), delete it with

  • -r is for recursive, so it will delete the folder and subfolders, even if it is non-empty
  • -f is for force (this might be unnecessary).

One thing to note is that the folder should be empty, then run the following command

Another thing to note is that the command your are typing should not start with a slash(/) not unless the folder is under root.

The last option and you should be very careful while using this one, is to force removal of the directory in question including any other files/directories in it.

For a beginner I would not recommend getting into the habit of using rm -Rf or rm -r -f , this will bite you in the face sooner or later. Safer would be to create a systemwide alias. Open terminal: Ctrl + Alt + T , then type:

So you get prompted before wiping out all your vacation photo’s by accident. The second recommendation I would like to add is to use rmdir , it will complain about non-empty directories and that is exactly what you want as a newbee.

But in the sense of the question, the answer is as given here already, use -f to erase a folder.

If you are sure that the directory exists, then:

To delete the entire directory to your folders and files

Источник

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

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

11 Answers 11

find can be a very good friend:

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:

Short answer

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)
Читайте также:  Gta vice city mac os big sur

Create 5 files as shown below:

List all files except z.txt

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

You can type it right in the command-line or use this keystroke in the script

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:

The script looks like (just a sketch):

At least in zsh

could be an option, if you only want to preserve one single file.

If it’s just one file, one simple way is to move that file to /tmp or something, rm -Rf the directory and then move it back. You could alias this as a simple command.

The other option is to do a find and then grep out what you don’t want (using -v or directly using one of find s predicates) and then rm ing the remaining files.

For a single file, I’d do the former. For anything more, I’d write something custom similar to what thkala said.

In bash you have the !() glob operator, which inverts the matched pattern. So to delete everything except the file my_file_name.txt , try this:

I don’t know of such a program, but I have wanted it in the past for some times. The basic syntax would be:

The program I have in mind has three modes:

  • exact matching (with the option -e )
  • glob matching (default, like shown in the above example)
  • regex matching (with the option -r )

It takes the patterns to be excluded from the command line, followed by the separator — , followed by the file names. Alternatively, the file names might be read from stdin (if the option -s is given), each on a line.

Such a program should not be hard to write, in either C or the Shell Command Language. And it makes a good excercise for learning the Unix basics. When you do it as a shell program, you have to watch for filenames containing whitespace and other special characters, of course.

Источник

Remove all files except some from a directory

When using sudo rm -r , how can I delete all files, with the exception of the following:

19 Answers 19

If you don’t specify -type f find will also list directories, which you may not want.

Or a more general solution using the very useful combination find | xargs :

for example, delete all non txt-files in the current directory:

The print0 and -0 combination is needed if there are spaces in any of the filenames that should be deleted.

The extglob (Extended Pattern Matching) needs to be enabled in BASH (if it’s not enabled):

find . | grep -v «excluded files criteria» | xargs rm

This will list all files in current directory, then list all those that don’t match your criteria (beware of it matching directory names) and then remove them.

Update: based on your edit, if you really want to delete everything from current directory except files you listed, this can be used:

It will create a backup directory /tmp_backup (you’ve got root privileges, right?), move files you listed to that directory, delete recursively everything in current directory (you know that you’re in the right directory, do you?), move back to current directory everything from /tmp_backup and finally, delete /tmp_backup .

I choose the backup directory to be in root, because if you’re trying to delete everything recursively from root, your system will have big problems.

Surely there are more elegant ways to do this, but this one is pretty straightforward.

Источник

Оцените статью