feat(user/zeropad.sh):Permit ignoring of file extension via arg
[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 [str fext]
4 # Example: zeropad.sh;
5 # zeropad.sh ".jpg";
6 # Version: 0.1.0
7
8 declare fext; # file extension
9
10 list_files() {
11 # Desc: Lists working directory file basenames
12 # Usage: list_files
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 '{}' \; ;
17 else
18 find . -mindepth 1 -maxdepth 1 -type f -exec basename '{}' \; \
19 | grep -E -- "${fext}$" ;
20 fi;
21 }; # list pwd file basenames
22 main () {
23 # Read file extension if provided
24 if [[ -n "$1" ]]; then
25 fext="$1";
26 fi;
27
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
31
32 # Loop over the files and rename them
33 while read -r file; do
34 re='^[0-9]+';
35 if [[ ! "$file" =~ $re ]]; then continue; fi;
36
37 # Extract the leading digits
38 digits="$(echo "$file" | sed 's/\([0-9]*\).*/\1/')";
39 # Zero-pad the digits
40 padded_digits="$(printf "%0${max_digits}d" "$digits")";
41 # Construct the new filename
42 new_file="${padded_digits}${file#${digits}}";
43 # Rename the file
44 if [[ "$file" == "$new_file" ]]; then continue; fi;
45 mv -n "$file" "$new_file"
46 # declare -p file new_file; # debug
47 done < <(list_files);
48 }; # main program
49
50 main "$@";
51
52 # Author: Steven Baltakatei Sandoval
53 # License: GPLv3+