From: Steven Baltakatei Sandoval Date: Mon, 15 Jul 2024 21:30:03 +0000 (+0000) Subject: feat(user/zeropad.sh):Use find instead of ls; use bash functions X-Git-Url: https://zdv2.bktei.com/gitweb/BK-2020-03.git/commitdiff_plain/91872e11095679453071cdc685883a85d2322ce2?hp=092f7e8e8372f7d0986978dbe7949124d99464b8 feat(user/zeropad.sh):Use find instead of ls; use bash functions --- diff --git a/user/zeropad.sh b/user/zeropad.sh index 57b56c6..369d8c0 100755 --- a/user/zeropad.sh +++ b/user/zeropad.sh @@ -1,27 +1,37 @@ #!/bin/bash # Desc: Zero-pad working dir files with initial digits for sorting # Usage: zeropad.sh -# Version: 0.0.3 - -# 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; - -# 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 - mv -n "$file" "$new_file" - # declare -p file new_file; # debug -done < <(find . -mindepth 1 -maxdepth 1 -type f); +# Version: 0.0.4 + +list_files() { + find . -mindepth 1 -maxdepth 1 -type f -exec basename '{}' \; ; +}; +main () { + # 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 + mv -n "$file" "$new_file" + # declare -p file new_file; # debug + done < <(list_files); +}; + +main "$@"; + + + # Author: Steven Baltakatei Sandoval # License: GPLv3+