A Collection of Useful Scripts

Simple but useful scripts to handle basic needs.

1. Reanme Files

This script is to sort and rename image files from 1.jpg to n.jpg.

rename.sh
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
#!/bin/bash

# Directory to process (default is current directory)
DIR="."

# Check if a directory is provided as an argument
if [ $# -eq 1 ]; then
DIR="$1"
fi

# Check if the directory exists
if [ ! -d "$DIR" ]; then
echo "Error: Directory '$DIR' does not exist."
exit 1
fi

# Change to the specified directory
cd "$DIR" || exit 1

# Create a temporary directory for intermediate files
TEMP_DIR=$(mktemp -d)
if [ ! -d "$TEMP_DIR" ]; then
echo "Error: Could not create temporary directory."
exit 1
fi

# Counter for renaming
count=1

# Find all image files, sort them by name, and rename
# Using ls without -t for alphabetical sorting
for file in $(ls *.{jpg,jpeg,png,JPG,JPEG,PNG} 2>/dev/null); do
# Skip if not a regular file
if [ ! -f "$file" ]; then
continue
fi

# Generate new filename
new_name="$count.jpg"

# Move to temp directory first to avoid overwriting
mv "$file" "$TEMP_DIR/$new_name" || {
echo "Error: Failed to move $file to temp directory."
exit 1
}

# Increment counter
((count++))
done

# Move files back from temp directory to original directory
mv "$TEMP_DIR"/* . 2>/dev/null
if [ $? -ne 0 ]; then
echo "Warning: Some files may not have been moved back."
fi

# Clean up temp directory
rmdir "$TEMP_DIR"

# Check if any files were renamed
if [ $count -eq 1 ]; then
echo "No image files found in '$DIR'."
else
echo "Renamed $((count-1)) image files in '$DIR'."
fi

exit 0
1
2
3
usage:

./rename [target folder]
Author

Joe Chu

Posted on

2025-02-18

Updated on

2025-03-09

Licensed under

Comments