feat(user/zeropad.sh):Permit ignoring of file extension via arg
[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
f48d0d55
SBS
3# Usage: zeropad.sh [str fext]
4# Example: zeropad.sh;
5# zeropad.sh ".jpg";
6# Version: 0.1.0
7
8declare fext; # file extension
91872e11
SBS
9
10list_files() {
733bcf95
SBS
11 # Desc: Lists working directory file basenames
12 # Usage: list_files
f48d0d55 13 # Input: fext var file extension
733bcf95 14 # Output: stdout a line-delimited list of file names
f48d0d55
SBS
15 if [[ -z "$fext" ]]; then
16 find . -mindepth 1 -maxdepth 1 -type f -exec basename '{}' \; ;
17 else
18 find . -mindepth 1 -maxdepth 1 -type f -exec basename '{}' \; \
19 | grep -E -- "${fext}$" ;
20 fi;
733bcf95 21}; # list pwd file basenames
91872e11 22main () {
f48d0d55
SBS
23 # Read file extension if provided
24 if [[ -n "$1" ]]; then
25 fext="$1";
26 fi;
27
91872e11
SBS
28 # Find the maximum number of leading digits in the filenames of working dir
29 max_digits="$(list_files | sed -e 's/[^0-9].*//' | awk '{ if(length > L) L=length } END { print L }')";
30 # declare -p max_digits; # debug
31
32 # Loop over the files and rename them
33 while read -r file; do
34 re='^[0-9]+';
35 if [[ ! "$file" =~ $re ]]; then continue; fi;
36
37 # Extract the leading digits
38 digits="$(echo "$file" | sed 's/\([0-9]*\).*/\1/')";
39 # Zero-pad the digits
40 padded_digits="$(printf "%0${max_digits}d" "$digits")";
41 # Construct the new filename
42 new_file="${padded_digits}${file#${digits}}";
43 # Rename the file
2d366827 44 if [[ "$file" == "$new_file" ]]; then continue; fi;
91872e11
SBS
45 mv -n "$file" "$new_file"
46 # declare -p file new_file; # debug
47 done < <(list_files);
733bcf95 48}; # main program
91872e11
SBS
49
50main "$@";
51
7328c729
SBS
52# Author: Steven Baltakatei Sandoval
53# License: GPLv3+