-
Notifications
You must be signed in to change notification settings - Fork 1
/
bulk-rename-qsort
45 lines (39 loc) · 1.12 KB
/
bulk-rename-qsort
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
#!/bin/bash
set -euo pipefail
fnd=' '; rpl='_'; dir=${1-${PWD}}
[[ ! -d ${dir} || ! -O ${dir} ]] && printf 'error with %q\n' "${dir}" >&2 && exit 1
[[ ${dir:0:1} != '/' ]] && dir=./${dir}
cd -- "${dir}"
function qsort(){
local i p sml=() lrg=()
qsort_res=()
(($#)) || return 0
p=${1}; shift
for i; do ((${p%% *} < ${i%% *})) && sml+=("${i}") || lrg+=("${i}"); done
qsort "${sml[@]}"; sml=("${qsort_res[@]}")
qsort "${lrg[@]}"; lrg=("${qsort_res[@]}")
qsort_res=("${sml[@]}" "${p#* }" "${lrg[@]}")
}
shopt -s globstar dotglob nullglob
depth=()
for fd in ./**/*"${fnd}"*; do
if [[ -d "${fd}" ]]; then
count=${fd//[^\/]}
depth+=("${#count} ${fd}")
elif [[ -f "${fd}" ]]; then
fname=${fd##*/}
fpath=${fd%/*}
newf=${fpath}/${fname//${fnd}/${rpl}}
[[ -e "${newf}" ]] && printf '%q already exists.. quitting\n' "${newf}" >&2 && exit 1
mv -- "${fd}" "${newf}"
fi
done
qsort "${depth[@]}"
declare qsort_res
for d in "${qsort_res[@]}"; do
dname=${d##*/}
dpath=${d%/*}
newd=${dpath}/${dname//${fnd}/${rpl}}
[[ -e "${newd}" ]] && printf '%q already exists.. quitting\n' "${newd}" >&2 && exit 1
mv -- "${d}" "${newd}"
done