Delete all but one file linux

3 Ways to Delete All Files in a Directory Except One or Few Files with Extensions

Sometimes you get into a situation where you need to delete all files in a directory or simply cleanup a directory by removing all files except files of a given type (ending with a particular extension).

In this article, we will show you how to delete files in a directory except certain file extensions or types using rm, find and globignore commands.

Before we move any further, let us start by briefly having a look at one important concept in Linux – filename pattern matching, which will enable us to deal with our issue at hand.

In Linux, a shell pattern is a string that consists of the following special characters, which are referred to as wildcards or metacharacters:

  1. * – matches zero or more characters
  2. ? – matches any single character
  3. [seq] – matches any character in seq
  4. [!seq] – matches any character not in seq

There are three possible methods we shall explore here, and these include:

Delete Files Using Extended Pattern Matching Operators

The different extended pattern matching operators are listed below, where pattern-list is a list containing one or more filenames, separated using the | character:

  1. *(pattern-list) – matches zero or more occurrences of the specified patterns
  2. ?(pattern-list) – matches zero or one occurrence of the specified patterns
  3. +(pattern-list) – matches one or more occurrences of the specified patterns
  4. @(pattern-list) – matches one of the specified patterns
  5. !(pattern-list) – matches anything except one of the given patterns

To use them, enable the extglob shell option as follows:

1. To delete all files in a directory except filename, type the command below:

Delete All Files Except One File in Linux

2. To delete all files with the exception of filename1 and filename2:

Delete All Files Except Few Files in Linux

3. The example below shows how to remove all files other than all .zip files interactively:

Delete All Files Except Zip Files in Linux

4. Next, you can delete all files in a directory apart from all .zip and .odt files as follows, while displaying what is being done:

Delete All Files Except Certain File Extensions

Once you have all the required commands, turn off the extglob shell option like so:

Delete Files Using Linux find Command

Under this method, we can use find command exclusively with appropriate options or in conjunction with xargs command by employing a pipeline as in the forms below:

5. The following command will delete all files apart from .gz files in the current directory:

Command find – Remove All Files Except .gz Files

6. Using a pipeline and xargs, you can modify the case above as follows:

Remove Files Using find and xargs Commands

7. Let us look at one additional example, the command below will wipe out all files excluding .gz , .odt , and .jpg files in the current directory:

Remove All Files Except File Extensions

Читайте также:  Windows command commands syntax

Delete Files Using Bash GLOBIGNORE Variable

This last approach however, only works with bash. Here, the GLOBIGNORE variable stores a colon-separated pattern-list (filenames) to be ignored by pathname expansion.

To employ this method, move into the directory that you wish to clean up, then set the GLOBIGNORE variable as follows:

In this instance, all files other than .odt , .iso , and .txt files with be removed from the current directory.

Now run the command to clean up the directory:

Afterwards, turn off GLOBIGNORE variable:

Delete Files Using Bash GLOBIGNORE Variable

Note: To understand the meaning of the flags employed in the commands above, refer to the man pages of each command we have used in the various illustrations.

Thats all! If you have any other command line techniques in mind for the same purpose, do not forget to share with us via our feedback section below.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

Remove only files in directory on linux NOT directories

What delete command can be run to remove only files in given directory

  • NOT directories
  • NOT sub-directories
  • NOT files in these sub-directories.

Some files don’t have extensions so rm *.* wont work.

There are thousands of files in this folder.

10 Answers 10

BUT this won’t prompt you for confirmation or output what it just deleted. Therefore best to run it without the -delete action first and check that they’re the correct files.

You can use find with -type f for files only and -maxdepth 1 so find won’t search for files in sub-directories of /path/to/directory . rm -i will prompt you on each delete so you can confirm or deny the delete. If you dont care about being asked for confirmation of each delete, change it to rm -fv ( -f for force the delete). The -v flag makes it so that with each delete, a message is printed saying what file was just deleted.

This should meet the criteria:

NOT directories
NOT subdirectories
NOT files in these subdirectories.

Since this is high on google search, the simplest answer is:

where $directoryPath is the directory you want to empty. Credits should go to cbm3384 (that for some reason has gotten negative votes for this answer, why?)

If you do not want to confirm:

If you don’t believe try man rm or

The above creates a directory structure, that has ‘helloX.txt’ in each folder (X is the directory level). rm 1/2/* deletes hello2.txt and leaves the other structure intact.

Also rm */*/* deletes only hello2.txt . It is the only that matches the pattern.

Just an example of a Makefile that cleans cakephp tmp-directory and leaves the directory structure intact:

Minus in front of the rm means «do not halt on errors» (unremoved directory returns an error). If you want some level to be saved, just remove that line, e.g. second rm line removes logs.

Let me know if you have a system that does something else (BSD?).

Источник

How to remove files and directories quickly via terminal (bash shell) [closed]

Want to improve this question? Update the question so it’s on-topic for Stack Overflow.

Читайте также:  Джава для mac os

Closed 6 years ago .

From terminal window:

When I use the rm command it can only remove files.
When I use the rmdir command it only removes empty folders.

If I have a directory nested with files and folders within folders with files and so on, is there any way to delete all the files and folders without all the strenuous command typing?

If it makes a difference, I am using the mac bash shell from terminal, not Microsoft DOS or linux.

4 Answers 4

-r «recursive» -f «force» (suppress confirmation messages)

Would remove everything (folders & files) in the current directory.

But be careful! Only execute this command if you are absolutely sure, that you are in the right directory.

Yes, there is. The -r option tells rm to be recursive, and remove the entire file hierarchy rooted at its arguments; in other words, if given a directory, it will remove all of its contents and then perform what is effectively an rmdir .

The other two options you should know are -i and -f . -i stands for interactive; it makes rm prompt you before deleting each and every file. -f stands for force; it goes ahead and deletes everything without asking. -i is safer, but -f is faster; only use it if you’re absolutely sure you’re deleting the right thing. You can specify these with -r or not; it’s an independent setting.

And as usual, you can combine switches: rm -r -i is just rm -ri , and rm -r -f is rm -rf .

Also note that what you’re learning applies to bash on every Unix OS: OS X, Linux, FreeBSD, etc. In fact, rm ‘s syntax is the same in pretty much every shell on every Unix OS. OS X, under the hood, is really a BSD Unix system.

Источник

How to remove all files from a directory?

The closest I’ve gotten is

but that doesn’t work for files that don’t have an extension.

9 Answers 9

Linux does not use extensions. It is up to the creator of the file to decide whether the name should have an extension. Linux looks at the first few bytes to figure out what kind of file it is dealing with.

To remove all non-hidden files* in a directory use:

However, this will show an error for each sub-directory, because in this mode it is only allowed to delete files.

To remove all non-hidden files and sub-directories (along with all of their contents) in a directory use:

* Hidden files and directories are those whose names start with . (dot) character, e.g.: .hidden-file or .hidden-directory/ . Note that, in Bash, if the dotglob option (which is off by default) is set, rm will act on hidden files too, because they will be included when * is expanded by the shell to provide the list of filename arguments.

To remove a folder with all its contents (including all interior folders):

To remove all the contents of the folder (including all interior folders) but not the folder itself:

or, if you want to make sure that hidden files/directories are also removed:

To remove all the «files» from inside a folder(not removing interior folders):

Warning: if you have spaces in your path, make sure to always use quotes.

is equivalent to 2 separate rm -rf calls:

To avoid this issue, you can use ‘ single-quotes ‘ (prevents all expansions, even of shell variables) or » double-quotes » (allows expansion of shell variables, but prevents other expansions):

  • rm — stands for remove
  • -f — stands for force which is helpful when you don’t want to be asked/prompted if you want to remove an archive, for example.
  • -r — stands for recursive which means that you want to go recursively down every folder and remove everything.
Читайте также:  Диспетчер задач линукс консоль

Источник

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)

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.

Источник

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