TheWebs
TheWebs

Reputation: 12923

Delete everything but a specific folder

I am wondering what options I would pass to rm -rf to remove all but the .git/ folder. I was reading the man pages but I got confused at the options you can pass in. If I wanted to remove all but the .git/ what about the command be?

Upvotes: 1

Views: 266

Answers (4)

Max
Max

Reputation: 701

Since you mention the .git/ directory, you are in a Git repository and could use git itself to remove folders and files:

git rm -r *

As desired, this would not remove the .git directory -- and if need be, you could also join this with find, xargs, grep etc. for a more precise selection of folders and files.

Also, perhaps hereafter you want to add and commit a new set of files:

git add --all
git commit -m "commit message"

Upvotes: 0

Gilles Quénot
Gilles Quénot

Reputation: 185053

With bash :

shopt -s extglob
rm -rf !(.git)

warning Take care to be in the good directory before running this command.

Check http://mywiki.wooledge.org/glob#extglob

Upvotes: 1

rastasheep
rastasheep

Reputation: 11222

You can do that using bash GLOBIGNORE variable to remove all files except specific ones

From the bash(1) page:

A colon-separated list of patterns defining the set of filenames to be ignored
by pathname expansion. If a filename matched by a pathname expansion pattern
also matches one of the patterns in GLOBIGNORE, it is removed from the list
of matches.

To delete all files except zip and iso files, set GLOBIGNORE as follows:

GLOBIGNORE=*.git
rm -rf *
unset GLOBIGNORE

PS. only works with BASH

Upvotes: 1

bgoldst
bgoldst

Reputation: 35314

One possible solution is to use find to find all items in the directory that are not .git and then rm them:

> find . -mindepth 1 -maxdepth 1 ! -name .git -print0| xargs -0 rm -rf;

Upvotes: 1

Related Questions