Commit | Line | Data |
---|---|---|
ab468b4d SBS |
1 | #!/bin/bash |
2 | # Desc: Zero-pad working dir files with initial digits for sorting | |
3 | # Usage: zeropad.sh | |
2d366827 | 4 | # Version: 0.0.5 |
91872e11 SBS |
5 | |
6 | list_files() { | |
733bcf95 SBS |
7 | # Desc: Lists working directory file basenames |
8 | # Usage: list_files | |
9 | # Input: none | |
10 | # Output: stdout a line-delimited list of file names | |
91872e11 | 11 | find . -mindepth 1 -maxdepth 1 -type f -exec basename '{}' \; ; |
733bcf95 | 12 | }; # list pwd file basenames |
91872e11 SBS |
13 | main () { |
14 | # Find the maximum number of leading digits in the filenames of working dir | |
15 | max_digits="$(list_files | sed -e 's/[^0-9].*//' | awk '{ if(length > L) L=length } END { print L }')"; | |
16 | # declare -p max_digits; # debug | |
17 | ||
18 | # Loop over the files and rename them | |
19 | while read -r file; do | |
20 | re='^[0-9]+'; | |
21 | if [[ ! "$file" =~ $re ]]; then continue; fi; | |
22 | ||
23 | # Extract the leading digits | |
24 | digits="$(echo "$file" | sed 's/\([0-9]*\).*/\1/')"; | |
25 | # Zero-pad the digits | |
26 | padded_digits="$(printf "%0${max_digits}d" "$digits")"; | |
27 | # Construct the new filename | |
28 | new_file="${padded_digits}${file#${digits}}"; | |
29 | # Rename the file | |
2d366827 | 30 | if [[ "$file" == "$new_file" ]]; then continue; fi; |
91872e11 SBS |
31 | mv -n "$file" "$new_file" |
32 | # declare -p file new_file; # debug | |
33 | done < <(list_files); | |
733bcf95 | 34 | }; # main program |
91872e11 SBS |
35 | |
36 | main "$@"; | |
37 | ||
7328c729 SBS |
38 | # Author: Steven Baltakatei Sandoval |
39 | # License: GPLv3+ |