blob: e7d0faeb3042e60bd0faeecd73f3ff7cf53edfb3 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
#!/bin/env bash
# dab - delete all but
# Craig Jennings <c@cjennings.net>
# deletes all files in current directory that are NOT of a specific extension
# default switch values
recurse=""
del_dirs=""
# help function
show_help() {
echo "Usage: $0 [extension] [OPTION]"
echo "Deletes all files that do not match the given extension from the current directory."
echo ""
echo "Options:"
echo "-r Delete files in directories recursively."
echo "-d Delete directories if they become empty after deletions."
echo "-h Display this help message and exit."
echo ""
echo "Example: $0 txt -r -d"
echo "This would delete all non-text files in the current directory and subdirectories. Any directories emptied by this process will also be deleted."
echo ""
echo "Note: Directories that were previously empty will remain untouched."
}
# if help was requested, show it and exit
if [[ $1 = "-h" ]] || [[ $2 = "-h" ]] || [[ $3 = "-h" ]]; then
show_help
exit
fi
# error if nothing or * was passed
if [[ -z $1 ]] || [[ $1 = "*" ]]; then
echo "ERROR: No file extension was provided or invalid extension ('*')."
show_help
exit
fi
# identify rest of arguments
ext=$1
if [[ $2 == *"-r"* ]] || [[ $3 == *"-r"* ]]; then
recurse="-R"
fi
if [[ $2 == *"-d"* ]] || [[ $3 == *"-d"* ]]; then
del_dirs="true"
fi
# Save empty directories into an array before deleting the files
empty_dirs=()
while IFS= read -r -d $'\0'; do
empty_dirs+=("$REPLY")
done < <(find . -type d -empty -print0)
shopt -s globstar nullglob extglob
# remove non-matching files
for file in **; do
if [[ -f "$file" ]] && [[ "$file" != *".$ext" ]]; then
rm "$file"
fi
done
# remove directories emptied by this operation
if [[ $del_dirs == "true" ]]; then
for dir in **/; do
if [[ ! -n "$(ls -A $dir)" ]] && [[ ! "${empty_dirs[*]}" =~ $dir ]]; then
rmdir "$dir"
fi
done
fi
|