Commit | Line | Data |
---|---|---|
ab468b4d SBS |
1 | #!/bin/bash |
2 | # Desc: Zero-pad working dir files with initial digits for sorting | |
3 | # Usage: zeropad.sh | |
91872e11 SBS |
4 | # Version: 0.0.4 |
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 | |
30 | mv -n "$file" "$new_file" | |
31 | # declare -p file new_file; # debug | |
32 | done < <(list_files); | |
733bcf95 | 33 | }; # main program |
91872e11 SBS |
34 | |
35 | main "$@"; | |
36 | ||
7328c729 SBS |
37 | # Author: Steven Baltakatei Sandoval |
38 | # License: GPLv3+ |