feat(user/ffmpeg_parallel_encode.sh):Add parallel | ffmpeg script
[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";
30f77d36 6# Input: arg1 str file extension of files to apply changes to
0564bc20 7# Version: 0.2.0
f48d0d55
SBS
8
9declare fext; # file extension
91872e11
SBS
10
11list_files() {
733bcf95
SBS
12 # Desc: Lists working directory file basenames
13 # Usage: list_files
f48d0d55 14 # Input: fext var file extension
733bcf95 15 # Output: stdout a line-delimited list of file names
f48d0d55
SBS
16 if [[ -z "$fext" ]]; then
17 find . -mindepth 1 -maxdepth 1 -type f -exec basename '{}' \; ;
18 else
19 find . -mindepth 1 -maxdepth 1 -type f -exec basename '{}' \; \
20 | grep -E -- "${fext}$" ;
21 fi;
733bcf95 22}; # list pwd file basenames
0564bc20
SBS
23remove_leading_zeroes() {
24 # Desc: Removes leading zeroes from lines
25 # Input: stdin
26 # Output: stdout
27 # Depends: BK-2020-03 read_stdin()
28 # Version: 0.0.1
29 while read -r line; do
30 printf "%s\n" "$line" | sed -E -e 's/(^0*)([0-9].*)/\2/';
31 done;
32};
33get_max_digits() {
34 # Desc: Returns max leading digits of pwd filenames
35 # Depends: list_files()
36 # BK-2020-03: remove_leading_zeroes()
37 # GNU sed 4.8
38 # GNU awk 5.1.0
39 local output;
40
41 # Find the maximum number of leading digits in the filenames of working dir
42 output="$(list_files | remove_leading_zeroes \
43 | awk '{ match($0, /^[0-9]+/); if (RLENGTH > max) max=RLENGTH } END { print max }' )";
44 # declare -p max_digits; # debug
45 printf "%s" "$output";
46}; # return max digits to stdout
91872e11 47main () {
f48d0d55
SBS
48 # Read file extension if provided
49 if [[ -n "$1" ]]; then
50 fext="$1";
51 fi;
52
0564bc20 53 max_digits="$(get_max_digits)";
91872e11
SBS
54
55 # Loop over the files and rename them
56 while read -r file; do
0564bc20 57 # Skip files with no leading digits
91872e11
SBS
58 re='^[0-9]+';
59 if [[ ! "$file" =~ $re ]]; then continue; fi;
60
61 # Extract the leading digits
0564bc20
SBS
62 digits="$(echo "$file" | sed -E 's/([0-9]*).*/\1/')"; # all leading digits
63 digits_nlz="$(echo "$digits" | remove_leading_zeroes)"; # no leading zeroes
91872e11 64 # Zero-pad the digits
0564bc20 65 padded_digits="$(printf "%0${max_digits}d" "$digits_nlz")";
91872e11
SBS
66 # Construct the new filename
67 new_file="${padded_digits}${file#${digits}}";
68 # Rename the file
2d366827 69 if [[ "$file" == "$new_file" ]]; then continue; fi;
0564bc20
SBS
70 mv -n "$file" "$new_file";
71 #declare -p max_digits file digits digits_nlz padded_digits new_file # debug
91872e11 72 done < <(list_files);
733bcf95 73}; # main program
91872e11
SBS
74
75main "$@";
76
7328c729
SBS
77# Author: Steven Baltakatei Sandoval
78# License: GPLv3+