feat(unitproc/bkt-get_path_hierarchy_level):Add bash function
[BK-2020-03.git] / user / zeropad.sh
... / ...
CommitLineData
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.2.0
8
9declare fext; # file extension
10
11list_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
23remove_leading_zeroes() {
24 # Desc: Removes leading zeroes from lines
25 # Input: stdin
26 # Output: stdout
27 # Depends: BK-2020-03 read_stdin()
28 # Version: 0.0.1
29 while read -r line; do
30 printf "%s\n" "$line" | sed -E -e 's/(^0*)([0-9].*)/\2/';
31 done;
32};
33get_max_digits() {
34 # Desc: Returns max leading digits of pwd filenames
35 # Depends: list_files()
36 # BK-2020-03: remove_leading_zeroes()
37 # GNU sed 4.8
38 # GNU awk 5.1.0
39 local output;
40
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
47main () {
48 # Read file extension if provided
49 if [[ -n "$1" ]]; then
50 fext="$1";
51 fi;
52
53 max_digits="$(get_max_digits)";
54
55 # Loop over the files and rename them
56 while read -r file; do
57 # Skip files with no leading digits
58 re='^[0-9]+';
59 if [[ ! "$file" =~ $re ]]; then continue; fi;
60
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
64 # Zero-pad the digits
65 padded_digits="$(printf "%0${max_digits}d" "$digits_nlz")";
66 # Construct the new filename
67 new_file="${padded_digits}${file#${digits}}";
68 # Rename the file
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
72 done < <(list_files);
73}; # main program
74
75main "$@";
76
77# Author: Steven Baltakatei Sandoval
78# License: GPLv3+