-
Notifications
You must be signed in to change notification settings - Fork 0
/
rename
executable file
·78 lines (70 loc) · 2.29 KB
/
rename
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
73
74
75
76
77
78
#!/usr/bin/env bash
#
# rename
# rename.ul replacement with different/better options
#
# desc
# debian removed rename.ul from its util-linux installation, so we have to
# write our own. while we're at it, we add a couple options to make
# it easier to to prepend or append something without needing empty string
# argument (which only works to append), although we still take one to allow
# the interface to be used the same way
#
# ref
# https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=982944
#
# scott@smemsh.net
# https://github.com/smemsh/utilsh/
# https://spdx.org/licenses/GPL-2.0
#
eval set -- $(getopt -n "${0##*/}" \
-o h1p:a:P:A: \
-l help,firstonly,prepend:,append:,unprepend:,unappend: \
-- "$@")
while true; do case $1 in
(-p|--prepend) prepend="$2"; shift 2;;
(-a|--append) append="$2"; shift 2;;
(-P|--unprepend) unprepend="$2"; shift 2;;
(-A|--unappend) unappend="$2"; shift 2;;
(-1|--firstonly) firstonly=1; shift;;
(-h|--help) cat <<-%
-p/--prepend <string to add to beginning>
-a/--append <string to add to end>
-P/--unprepend <string to remove from beginning>
-A/--unappend <string to remove from end>
%
echo "read script for more usage" >&2; false; exit;;
(--) shift; break;;
(*) echo "impossible condition" >&2; false; exit;;
esac; done
###
for v in append prepend unprepend unappend
do let has_$v=0; done
if [[ $append ]]; then has_append=1; to="$append"
elif [[ $prepend ]]; then has_prepend=1
elif [[ $unprepend ]]; then has_unprepend=1
elif [[ $unappend ]]; then has_unappend=1
else from="$1"; to="$2"; shift 2
fi
optsum=$((has_prepend + has_append + has_unprepend + has_unappend))
if ((optsum && optsum != 1))
then echo "only one operation at a time is supported" >&2; false; exit; fi
for file
do
if [[ $file == '.' || $file == '..' ]]
then echo "skipping '$file'" >&2; continue; fi
if [[ $file =~ '/' ]]
then echo "skipping path '$file'" >&2; continue; fi
if ((has_prepend)); then newname="$prepend$file"
elif ((has_unprepend)); then newname="${file/#$unprepend/}"
elif ((has_unappend)); then newname="${file/%$unappend/}"
elif [[ $from == '' ]] || ((has_append)); then newname="$file$to"
else
if ((firstonly))
then newname="${file/$from/$to}"
else newname="${file//$from/$to}"
fi
fi
if ! mv "$file" "$newname"
then echo "failed to mv '$file' '$newname'"; false; fi
done