nachocab
nachocab

Reputation: 14374

How to delete folders that don't contain a given file in zsh?

I'm looking for a way to delete all the folders in a given path that don't contain a given file. For example, using the following directory structure:

mkdir -p 1 2 3 4
touch 1/{a,b,c} 2/{b,d} 3/{a,c} 4/{a,c,d}
ls *
# directory_structure
# 1:
# a  b  c

# 2:
# b  d

# 3:
# a  c

# 4:
# a  c  d

I'd want to delete folders 3 and 4 because those are the ones that don't contain file b. What's the best way of doing that in zsh?

Upvotes: 0

Views: 114

Answers (2)

Kevin
Kevin

Reputation: 56089

Because zsh is awesome, you can execute a command to test each file in a glob. Here you want *(e:[ \! -e '$REPLY'/b ]:):

% tree
.
├── 1
│   ├── a
│   ├── b
│   └── c
├── 2
│   ├── b
│   └── d
├── 3
│   ├── a
│   └── c
└── 4
    ├── a
    ├── c
    └── d

4 directories, 10 files
% rm -r *(e:[ \! -e '$REPLY'/b ]:)
% tree
.
├── 1
│   ├── a
│   ├── b
│   └── c
└── 2
    ├── b
    └── d

2 directories, 5 files

Upvotes: 2

Jokester
Jokester

Reputation: 5617

Disclaimer: I'm not a heavy zsh user, there must be better way in zsh script.

for dir in 1 2 3 4 ; do
  [ -e $dir/b ] || rm -r $dir
done

Upvotes: 1

Related Questions