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