feat(unitproc/bkt-remove_leading_zeroes):Add bash function
[BK-2020-03.git] / user / zeropad.sh
index 57b56c65b4a8dedaf87309f8a6f52083932f43cd..b9b032b1465f750528dc72edccfe6878100109e0 100755 (executable)
@@ -1,27 +1,54 @@
 #!/bin/bash
 # Desc: Zero-pad working dir files with initial digits for sorting
 #!/bin/bash
 # Desc: Zero-pad working dir files with initial digits for sorting
-# Usage: zeropad.sh
-# Version: 0.0.3
+# Usage: zeropad.sh [str fext]
+# Example: zeropad.sh;
+#          zeropad.sh ".jpg";
+# Input: arg1  str  file extension of files to apply changes to
+# Version: 0.1.1
 
 
-# Find the maximum number of leading digits in the filenames of working dir
-max_digits="$(ls -1 * | sed 's/[^0-9].*//' | awk '{ if(length > L) L=length } END { print L }')";
-declare -p max_digits;
+declare fext; # file extension
 
 
-# Loop over the files and rename them
-while read -r file; do
-    re='^[0-9]+';
-    if [[ ! "$file" =~ $re ]]; then continue; fi;
+list_files() {
+    # Desc: Lists working directory file basenames
+    # Usage: list_files
+    # Input: fext  var  file extension
+    # Output: stdout  a line-delimited list of file names
+    if [[ -z "$fext" ]]; then
+        find . -mindepth 1 -maxdepth 1 -type f -exec basename '{}' \; ;
+    else
+        find . -mindepth 1 -maxdepth 1 -type f -exec basename '{}' \; \
+            | grep -E -- "${fext}$" ;
+    fi;
+}; # list pwd file basenames
+main () {
+    # Read file extension if provided
+    if [[ -n "$1" ]]; then
+        fext="$1";
+    fi;
 
 
-    # Extract the leading digits
-    digits="$(echo "$file" | sed 's/\([0-9]*\).*/\1/')";
-    # Zero-pad the digits
-    padded_digits="$(printf "%0${max_digits}d" "$digits")";
-    # Construct the new filename
-    new_file="${padded_digits}${file#${digits}}";
-    # Rename the file
-    mv -n "$file" "$new_file"
-    # declare -p file new_file; # debug
-done < <(find . -mindepth 1 -maxdepth 1 -type f);
+    # Find the maximum number of leading digits in the filenames of working dir
+    max_digits="$(list_files | sed -e 's/[^0-9].*//' | awk '{ if(length > L) L=length } END { print L }')";
+    # declare -p max_digits; # debug
+
+    # Loop over the files and rename them
+    while read -r file; do
+        re='^[0-9]+';
+        if [[ ! "$file" =~ $re ]]; then continue; fi;
+
+        # Extract the leading digits
+        digits="$(echo "$file" | sed 's/\([0-9]*\).*/\1/')";
+        # Zero-pad the digits
+        padded_digits="$(printf "%0${max_digits}d" "$digits")";
+        # Construct the new filename
+        new_file="${padded_digits}${file#${digits}}";
+        # Rename the file
+        if [[ "$file" == "$new_file" ]]; then continue; fi;
+        mv -n "$file" "$new_file"
+        # declare -p file new_file; # debug
+    done < <(list_files);
+}; # main program
+
+main "$@";
 
 # Author: Steven Baltakatei Sandoval
 # License: GPLv3+
 
 # Author: Steven Baltakatei Sandoval
 # License: GPLv3+