Delete all directories except one

So, using a shell and having a directory:

./parent
./parent/one
./parent/two
./parent/three
./parent/four

I want to do something like rm -rf parent/*in one command, but keeping one directory, for example, "four", so the end result will be

./parent
./parent/four
+4
source share
1 answer

With, bashyou can do this with the option extglob shopt.

shopt -s extglob
cd parent
rm -rf !(four)

Using posix shell, I think you can use a loop for this

for dir in ./parent/*; do
    [ "$dir" = "four" ] && continue
    rm -rf "$dir"
done

or use an array to run rmonly once (but this requires arrays or with "$@")

arr=()
for dir in ./parent/*; do
    [ "$dir" = "four" ] && continue
    arr+=("$dir")
done
rm -rf "${arr[@]}"

or

for dir in ./parent/*; do
    [ "$dir" = "four" ] && continue
    set -- "$@" "$dir"
done
rm -rf "$@"

or you can use find

find ./parent -mindepth 1 -name four -prune -o -exec rm -rf {} \;

or (c find, which has -exec +to be saved when performing some rm)

find ./parent -mindepth 1 -name four -prune -o -exec rm -rf {} +

, , ,

rm -rf parent/*<ctrl-x>*

parent/four enter, <ctrl-x>* readline glob-expand-word.

+13

Source: https://habr.com/ru/post/1618362/


All Articles