You can use GLOBIGNORE
to set the names that will be ignored while globbing and then use *
to match all other files/directories:
GLOBIGNORE='a:b:x'; rm -r *
Example:
$ tree
.
├── a
│ ├── 1
│ ├── 2
│ └── 3
├── b
│ ├── 1
│ ├── 2
│ └── 3
├── c
│ ├── 1
│ ├── 2
│ └── 3
├── x
├── y
└── z
/NASA$ GLOBIGNORE='a:b:x'
/NASA$ rm -r *
/NASA$ tree
.
├── a
│ ├── 1
│ ├── 2
│ └── 3
├── b
│ ├── 1
│ ├── 2
│ └── 3
└── x
Alternately, you can use find
, from the NASA
directory:
find . -maxdepth 1 ! -name '.' ! -regex '.*/\(a\|b\|x\)$' -exec rm -r {} +
Example:
/NASA$ tree
.
├── a
│ ├── 1
│ ├── 2
│ └── 3
├── b
│ ├── 1
│ ├── 2
│ └── 3
├── c
│ ├── 1
│ ├── 2
│ └── 3
├── x
├── y
└── z
/NASA$ find . -maxdepth 1 ! -name '.' ! -regex '.*/\(a\|b\|x\)$' -exec rm -r {} +
/NASA$ tree
.
├── a
│ ├── 1
│ ├── 2
│ └── 3
├── b
│ ├── 1
│ ├── 2
│ └── 3
└── x
From man find
-empty File is empty and is either a regular file or a directory.
So to find both empty files and directories it is sufficient to do
find ~/lists -empty
To indicate the type, you could use the %y
output format specifier
%y File's type (like in ls -l), U=unknown type (shouldn't happen)
e.g.
find ~/lists -empty -printf '%y %p\n'
or make use of an external program like ls
, which includes a --classify
option
-F, --classify
append indicator (one of */=>@|) to entries
i.e.
find ~/lists -empty -exec ls -Fd {} \;
If your definition of 'empty' is expanded to include files containing only whitespace characters, then it becomes more complicated - and more computationally intensive, since now you need to actually open at least any non-empty files and examine their contents. The most efficient way I can think of off the top of my head would be something like
find ~/list \( -empty -o \( -type f -a ! -exec grep -qm1 '[^[:blank:]]' {} \; \) \) -exec ls -Fd {} \;
(either empty, OR a file AND grep does not detect at least one non-blank character). Likely there is a better way though.
Best Answer
Here is a straight-forward solution in bash, which analyzes the size of both files and folders:
first param is the target folder to examine
second param is the limit in kilobytes, where 1K=1024 bytes.