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