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
23 remove_leading_zeroes
() {
24 # Desc: Removes leading zeroes from lines
27 # Depends: BK-2020-03 read_stdin()
29 while read -r line
; do
30 printf "%s\n" "$line" |
sed -E -e 's/(^0*)([0-9].*)/\2/';
34 # Desc: Returns max leading digits of pwd filenames
35 # Depends: list_files()
36 # BK-2020-03: remove_leading_zeroes()
41 # Find the maximum number of leading digits in the filenames of working dir
42 output
="$(list_files | remove_leading_zeroes \
43 | awk '{ match($0, /^[0-9]+/); if (RLENGTH > max) max=RLENGTH } END { print max }' )";
44 # declare -p max_digits; # debug
45 printf "%s" "$output";
46 }; # return max digits to stdout
48 # Read file extension if provided
49 if [[ -n "$1" ]]; then
53 max_digits
="$(get_max_digits)";
55 # Loop over the files and rename them
56 while read -r file; do
57 # Skip files with no leading digits
59 if [[ ! "$file" =~
$re ]]; then continue; fi;
61 # Extract the leading digits
62 digits
="$(echo "$file" | sed -E 's/([0-9]*).*/\1/')"; # all leading digits
63 digits_nlz
="$(echo "$digits" | remove_leading_zeroes)"; # no leading zeroes
65 padded_digits
="$(printf "%0${max_digits}d
" "$digits_nlz")";
66 # Construct the new filename
67 new_file
="${padded_digits}${file#${digits}}";
69 if [[ "$file" == "$new_file" ]]; then continue; fi;
70 mv -n "$file" "$new_file";
71 #declare -p max_digits file digits digits_nlz padded_digits new_file # debug
77 # Author: Steven Baltakatei Sandoval