I looking for a command or bash script to delete all folders except if they have a specific file type (*.pdf) in the first level subfolder.
folder01
a.txt
y.txt
folder02
b.pdf
z.txt
folder03
h.txt
folder03.1
c.pdf
In the example above folder01 and folder03 needs to be deleted.
My attempt:
#!/bin/bash
shopt -s globstar
Loop through every subdirectory.
for d in */; do
f=("$d"/)
if [[ -f "$f" && ! "${f##/}" =~ ^.pdf$ ]]; then
# echo to ensure a test run; remove when verified.
echo rm -r -- "$d"
fi
done
file -b --mime-type …that may printapplication/pdfregardless of the filename). If so, what iffoo.pdfhappens to be a directory? or a symlink? (In other words: do files of types other than regular file count?) – Kamil Maciorowski Sep 07 '22 at 20:27xxx.pdf. I can assure you, it's safe to use *.pdf as the main rule. – Joel Sep 07 '22 at 20:41folder02. When consideringfolder02as the folder, what is the "first level subfolder" that would trigger the exception? OTOH infolder03folder03.1is a "first level subfolder" and there is a matching file in it; so why "folder03needs to be deleted"? Do you mean "to delete all folders except if a folder has a specific file type (*.pdf) directly in it (i.e. not in a subfolder)"? – Kamil Maciorowski Sep 07 '22 at 21:22Folder03will be deleted because it doesn’t have any pdf files directly inside it at level 1. Yes, it has a sub directory that havec.pdf, but I don’t care about any other levels, andFolder03needs to be deleted. – Joel Sep 08 '22 at 11:30