e008b7192fe19355ab1fbbae1b34bd40853708af
[BK-2020-03.git] / user / zeropad.sh
1 #!/bin/bash
2 # Desc: Zero-pad working dir files with initial digits for sorting
3 # Usage: zeropad.sh
4 # Version: 0.0.5
5
6 list_files() {
7 # Desc: Lists working directory file basenames
8 # Usage: list_files
9 # Input: none
10 # Output: stdout a line-delimited list of file names
11 find . -mindepth 1 -maxdepth 1 -type f -exec basename '{}' \; ;
12 }; # list pwd file basenames
13 main () {
14 # Find the maximum number of leading digits in the filenames of working dir
15 max_digits="$(list_files | sed -e 's/[^0-9].*//' | awk '{ if(length > L) L=length } END { print L }')";
16 # declare -p max_digits; # debug
17
18 # Loop over the files and rename them
19 while read -r file; do
20 re='^[0-9]+';
21 if [[ ! "$file" =~ $re ]]; then continue; fi;
22
23 # Extract the leading digits
24 digits="$(echo "$file" | sed 's/\([0-9]*\).*/\1/')";
25 # Zero-pad the digits
26 padded_digits="$(printf "%0${max_digits}d" "$digits")";
27 # Construct the new filename
28 new_file="${padded_digits}${file#${digits}}";
29 # Rename the file
30 if [[ "$file" == "$new_file" ]]; then continue; fi;
31 mv -n "$file" "$new_file"
32 # declare -p file new_file; # debug
33 done < <(list_files);
34 }; # main program
35
36 main "$@";
37
38 # Author: Steven Baltakatei Sandoval
39 # License: GPLv3+