feat(user/zeropad.sh):Use find instead of ls; use bash functions
[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
4# Version: 0.0.4
5
6list_files() {
7 find . -mindepth 1 -maxdepth 1 -type f -exec basename '{}' \; ;
8};
9main () {
10 # Find the maximum number of leading digits in the filenames of working dir
11 max_digits="$(list_files | sed -e 's/[^0-9].*//' | awk '{ if(length > L) L=length } END { print L }')";
12 # declare -p max_digits; # debug
13
14 # Loop over the files and rename them
15 while read -r file; do
16 re='^[0-9]+';
17 if [[ ! "$file" =~ $re ]]; then continue; fi;
18
19 # Extract the leading digits
20 digits="$(echo "$file" | sed 's/\([0-9]*\).*/\1/')";
21 # Zero-pad the digits
22 padded_digits="$(printf "%0${max_digits}d" "$digits")";
23 # Construct the new filename
24 new_file="${padded_digits}${file#${digits}}";
25 # Rename the file
26 mv -n "$file" "$new_file"
27 # declare -p file new_file; # debug
28 done < <(list_files);
29};
30
31main "$@";
32
33
34
35
36# Author: Steven Baltakatei Sandoval
37# License: GPLv3+