2 # Desc: Zero-pad working dir files with initial digits for sorting
3 # Usage: zeropad.sh [str fext]
6 # Input: arg1 str file extension of files to apply changes to
9 declare fext
; # file extension
12 # Desc: Lists working directory file basenames
14 # Input: fext var file extension
15 # Output: stdout a line-delimited list of file names
16 if [[ -z "$fext" ]]; then
17 find .
-mindepth 1 -maxdepth 1 -type f
-exec basename '{}' \
; ;
19 find .
-mindepth 1 -maxdepth 1 -type f
-exec basename '{}' \
; \
20 |
grep -E -- "${fext}$" ;
22 }; # list pwd file basenames
24 # Read file extension if provided
25 if [[ -n "$1" ]]; then
29 # Find the maximum number of leading digits in the filenames of working dir
30 max_digits
="$(list_files | sed -e 's/[^0-9].*//' | awk '{ if(length > L) L=length } END { print L }')";
31 # declare -p max_digits; # debug
33 # Loop over the files and rename them
34 while read -r file; do
36 if [[ ! "$file" =~
$re ]]; then continue; fi;
38 # Extract the leading digits
39 digits
="$(echo "$file" | sed 's/\([0-9]*\).*/\1/')";
41 padded_digits
="$(printf "%0${max_digits}d
" "$digits")";
42 # Construct the new filename
43 new_file
="${padded_digits}${file#${digits}}";
45 if [[ "$file" == "$new_file" ]]; then continue; fi;
46 mv -n "$file" "$new_file"
47 # declare -p file new_file; # debug
53 # Author: Steven Baltakatei Sandoval