fix(user/zeropad.sh):Only zero-pad files with leading digits
[BK-2020-03.git] / user / zeropad.sh
index 903960266b88c66b148bdedf8f1e51e09ab8dba1..57b56c65b4a8dedaf87309f8a6f52083932f43cd 100755 (executable)
@@ -1,23 +1,27 @@
 #!/bin/bash
 # Desc: Zero-pad working dir files with initial digits for sorting
 # Usage: zeropad.sh
 #!/bin/bash
 # Desc: Zero-pad working dir files with initial digits for sorting
 # Usage: zeropad.sh
-# Version: 0.0.1
+# Version: 0.0.3
 
 # Find the maximum number of leading digits in the filenames of working dir
 
 # 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 }');
+max_digits="$(ls -1 * | sed 's/[^0-9].*//' | awk '{ if(length > L) L=length } END { print L }')";
 declare -p max_digits;
 
 # Loop over the files and rename them
 declare -p max_digits;
 
 # Loop over the files and rename them
-for file in *; do
-  # 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;
+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
+    mv -n "$file" "$new_file"
+    # declare -p file new_file; # debug
+done < <(find . -mindepth 1 -maxdepth 1 -type f);
 
 
+# Author: Steven Baltakatei Sandoval
+# License: GPLv3+