Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all files and directories but certain ones using Bash

I'm writing a script that needs to erase everything from a directory except two directories, mysql and temp.

I've tried this:

ls * | grep -v mysql | grep -v temp | xargs rm -rf

but this also keeps all the files that have mysql in their name, that i don't need. it also doesn't delete any other directories.

any ideas?

like image 635
Bobo Avatar asked Jul 30 '13 23:07

Bobo


People also ask

How do I delete all files except one?

Using Extended Globbing and Pattern Matching Operators Also, with the ! operator, we can exclude all files we don't want glob to match during deletion. Let's look at the list of pattern matching operators: ?(pattern-list) matches at least zero and at most one occurrence.

How do I delete all files from a certain name?

To delete matching files: enter *_bad. jpg in the search box, select the results and press Delete or Del.

How do I delete all files from a specific type in Linux?

Using rm Command The 'rm' command is a basic command-line utility in Linux to remove sockets, pipes, device nodes, symbolic links, directories, system files, etc. To remove a file with a particular extension, use the command 'rm'.

How do you delete a directory and its all contents in terminal?

Delete a Directory ( rm -r ) To delete (i.e. remove) a directory and all the sub-directories and files that it contains, navigate to its parent directory, and then use the command rm -r followed by the name of the directory you want to delete (e.g. rm -r directory-name ).


2 Answers

You may try:

rm -rf !(mysql|init)

Which is POSIX defined:

 Glob patterns can also contain pattern lists. A pattern list is a sequence
of one or more patterns separated by either | or &. ... The following list
describes valid sub-patterns.

...
!(pattern-list):
    Matches any string that does not match the specified pattern-list.
...

Note: Please, take time to test it first! Either create some test folder, or simply echo the parameter substitution, as duly noted by @mnagel:

echo !(mysql|init)

Adding useful information: if the matching is not active, you may to enable/disable it by using:

shopt extglob                   # shows extglob status
shopt -s extglob                # enables extglob
shopt -u extglob                # disables extglob
like image 122
Rubens Avatar answered Sep 30 '22 18:09

Rubens


This is usually a job for find. Try the following command (add -rf if you need a recursive delete):

find . -maxdepth 1 \! \( -name mysql -o -name temp \) -exec rm '{}' \;

(That is, find entries in . but not subdirectories that are not [named mysql or named tmp] and call rm on them.)

like image 33
chrylis -cautiouslyoptimistic- Avatar answered Sep 30 '22 16:09

chrylis -cautiouslyoptimistic-