Renumber Sequential Files Script

goto script;

This script will rename all the files in the directory specified (not recursive) sequentially. It's written to preserve the original file order, and can work on all kinds of filenames. Note that it uses natural sort to determine original file order.

Examples

Rename all of the .jpg files in pictures/ to pic-???.jpg:

...
1.jpg
4.jpg
abc.jpg
abc.txt
...
./renumber-sequential pictures --find "*.jpg" --prefix "pic-" --suffix ".jpg" --padzeros --padlen 3

Results:

...
pic-001.jpg
pic-002.jpg
pic-003.jpg
abc.txt
...

Download:

file icon renumber_sequential2.0 KB

renumber-sequential:

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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#!/bin/bash

findexpr="*"
prefixfname=""
suffixfname=""
padzeros="n"
padlen="3"
verbose=0

helpmsg()
{
	echo "Usage: renumber_sequential [dir] options..."
	echo "  -f, --find [pat]       only rename files with this pattern"
	echo "  -p, --prefix [name]    prefix for all new filenames"
	echo "  -s, --suffix [name]    suffix/extension for all new filenames"
	echo "  -z, --padzeros         pad the new filenames with zeros"
	echo "  -l, --padlen [num]     padding length"
	echo "  -v, --verbose          verbose mode"
}

POSITIONAL=()
while [[ $# -gt 0 ]]; do
	arg="$1"

	case $arg in
		-h|--help)
			helpmsg
			exit
		;;
		-f|--find)
			findexpr="$2"
			shift
			shift
		;;
		-p|--prefix)
			prefixfname="$2"
			shift
			shift
		;;
		-s|--suffix)
			suffixfname="$2"
			shift
			shift
		;;
		-z|--padzeros)
			padzeros="y"
			shift
		;;
		-l|--padlen)
			padlen="$2"
			shift
			shift
		;;
		-v|--verbose)
			verbose=1
			shift
		;;
		*)
			POSITIONAL+=("$1")
			shift
		;;
	esac
done
set -- "${POSITIONAL[@]}"

mvargs=()

[ $verbose -ge 1 ] && mvargs+=("-v")

if [ $# -eq 0 ]; then
	helpmsg
	exit
fi

build_name()
{
	local counter="$1"

	local newf="$directory/$prefixfname"
	if [ "$padzeros" = "y" ]; then
		newf="${newf}$(printf "%0${padlen}d" $counter)"
	else
		newf="${newf}$(printf "%d" $counter)"
	fi

	echo "${newf}${suffixfname}"
}

#strip trailing slash
directory="${1%/}"

sessionprefix="rsp-$RANDOM."
counter=1

find "$directory" -maxdepth 1 -type f -name "$findexpr" -print0 | sort -zV | while IFS= read -r -d '' fname; do
	tmpname="${sessionprefix}$counter-$(date +'%Y-%m-%dT%H:%M:%S.%N')"
	while [ -f "$tmpname" ]; do
		tmpname="${sessionprefix}$counter-$(date +'%Y-%m-%dT%H:%M:%S.%N')-$RANDOM"
	done

	((counter++))

	mv ${mvargs[@]} -- "$fname" "$tmpname"
done

counter=1

find "$directory" -maxdepth 1 -type f -name "${sessionprefix}*" -print0 | sort -zV | while IFS= read -r -d '' fname; do
	mv ${mvargs[@]} -- "$fname" "$(build_name $counter)"
	((counter++))
done