-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathseren
executable file
·90 lines (80 loc) · 2.28 KB
/
seren
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
79
80
81
82
83
84
85
86
87
88
89
90
#!/bin/bash
readonly program="$(basename "${0}")"
IFS=$'\n'
# Instructions on how to use the script
# Shown with '-h', or when no arguments are given
function usage {
echo "
Usage:
${program} [options] <files>
Options:
-s <num>, --starting-number <num> Sets starting number for the sequence (defaults to 1).
-l <num>, --leading-zeros <num> Sets the amount of leading zeros (defaults to what'll accomodate the number of files).
-p <string>, --prepend <string> Sets name to prepend to the sequence number (defaults to nothing).
-a <string>, --append <string> Sets name to append to the sequence number (defaults to nothing).
-v, --verbose Be verbose.
-h, --help Show this message.
" | sed -E 's/^ {4}//'
}
if [[ "${#}" -eq 0 ]]; then
usage
exit 1
fi
# Options
args=()
while [[ "${1}" ]]; do
case "${1}" in
-h | --help)
usage
exit 0
;;
-s | --starting-number)
starting_num="${2}"
shift
;;
-l | --leading-zeros)
sequence_length="$(bc <<< "${2} + 1")"
shift
;;
-p | --prepend)
string_to_prepend="${2}"
shift
;;
-a | --append)
string_to_append="${2}"
shift
;;
-v | --verbose)
be_verbose="v"
;;
--)
shift
args+=("${@}")
break
;;
-*)
echo "Unrecognised option: ${1}"
exit 1
;;
*)
args+=("${1}")
;;
esac
shift
done
set -- "${args[@]}"
# Determines the starting number, depending on if one was picked
num="$([[ -n "${starting_num}" ]] && bc <<< "${starting_num} - 1" || echo '0')"
# If no sequence length is given,
# it will be set accordingly to what the last number
# in the sequence is (depending on the starting number)
if [[ -z "${sequence_length}" ]]; then
sequence_end="$(bc <<< "${#} + ${num}")"
sequence_length="${#sequence_end}"
fi
# The actual renaming part
for file_to_rename in "${@}"; do
num="$(printf "%.${sequence_length}d" "$(bc <<< "${num} + 1")")"
file_extension="$([[ "${file_to_rename}" = *.* ]] && echo ".${file_to_rename##*.}" || echo '')"
mv -n"${be_verbose}" "${file_to_rename}" "$(dirname "${file_to_rename}")/${string_to_prepend}${num}${string_to_append}${file_extension}"
done