fix(user/zeropad.sh):Only zero-pad files with leading digits
[BK-2020-03.git] / user / zeropad.sh
CommitLineData
ab468b4d
SBS
1#!/bin/bash
2# Desc: Zero-pad working dir files with initial digits for sorting
3# Usage: zeropad.sh
092f7e8e 4# Version: 0.0.3
ab468b4d
SBS
5
6# Find the maximum number of leading digits in the filenames of working dir
7328c729 7max_digits="$(ls -1 * | sed 's/[^0-9].*//' | awk '{ if(length > L) L=length } END { print L }')";
ab468b4d
SBS
8declare -p max_digits;
9
10# Loop over the files and rename them
092f7e8e
SBS
11while read -r file; do
12 re='^[0-9]+';
13 if [[ ! "$file" =~ $re ]]; then continue; fi;
14
15 # Extract the leading digits
16 digits="$(echo "$file" | sed 's/\([0-9]*\).*/\1/')";
17 # Zero-pad the digits
18 padded_digits="$(printf "%0${max_digits}d" "$digits")";
19 # Construct the new filename
20 new_file="${padded_digits}${file#${digits}}";
21 # Rename the file
22 mv -n "$file" "$new_file"
23 # declare -p file new_file; # debug
24done < <(find . -mindepth 1 -maxdepth 1 -type f);
ab468b4d 25
7328c729
SBS
26# Author: Steven Baltakatei Sandoval
27# License: GPLv3+