blob: f2f5004f629692ec1fd40fc63172840063fe308b (
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
|
#!/bin/bash
# Credit:
# Mitsuo, GPT4
# 2023年 11月 8日 水曜日 15:46:55 -05
# Check for proper number of command line args.
expected_args=3
if [ $# -ne $expected_args ]; then
echo "Usage: $1 {prefix} {date in yyyy-mm-dd format} {file extension, e.g., jpg}"
exit 1
fi
# Assign command line args to variables
prefix=$1
current_date=$2
extension=$3
# Validations
if ! [[ $current_date =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; then
echo "Date format is invalid. Please use yyyy-mm-dd format."
exit 1
fi
if [[ $extension == .* ]]; then
echo "Please provide the file extension without a leading period."
exit 1
fi
if [[ -z $prefix ]]; then
echo "Please provide a non-empty prefix."
exit 1
fi
# Loop through all files with the given extension in the current directory
#
# By default, if you use a pattern that doesn't match any filenames (like *.jpg
# when there are no .jpg files), bash will pass the pattern itself as an
# argument to commands. For example, if there are no .jpg files in your
# directory and you use the *.jpg pattern in a loop or command, the loop or
# command will receive *.jpg as an input, which is probably not what you want.
shopt -s nullglob
i=1
for file in *$extension; do
# Skip if the file is not a regular file
if [[ ! -f $file ]]; then
continue
fi
# Generate the correlative number with leading zeros
printf -v suffix "%02d" $i
# Rename the file (-- is end of command line options)
mv -- "$file" "${prefix}-${current_date}_${suffix}.${extension}"
# Increment the counter
((i++))
done
shopt -u nullglob
echo "Renaming complete!"
|