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() { | |
7 | find . -mindepth 1 -maxdepth 1 -type f -exec basename '{}' \; ; | |
8 | }; | |
9 | main () { | |
10 | # Find the maximum number of leading digits in the filenames of working dir | |
11 | max_digits="$(list_files | sed -e 's/[^0-9].*//' | awk '{ if(length > L) L=length } END { print L }')"; | |
12 | # declare -p max_digits; # debug | |
13 | ||
14 | # Loop over the files and rename them | |
15 | while read -r file; do | |
16 | re='^[0-9]+'; | |
17 | if [[ ! "$file" =~ $re ]]; then continue; fi; | |
18 | ||
19 | # Extract the leading digits | |
20 | digits="$(echo "$file" | sed 's/\([0-9]*\).*/\1/')"; | |
21 | # Zero-pad the digits | |
22 | padded_digits="$(printf "%0${max_digits}d" "$digits")"; | |
23 | # Construct the new filename | |
24 | new_file="${padded_digits}${file#${digits}}"; | |
25 | # Rename the file | |
26 | mv -n "$file" "$new_file" | |
27 | # declare -p file new_file; # debug | |
28 | done < <(list_files); | |
29 | }; | |
30 | ||
31 | main "$@"; | |
32 | ||
33 | ||
34 | ||
ab468b4d | 35 | |
7328c729 SBS |
36 | # Author: Steven Baltakatei Sandoval |
37 | # License: GPLv3+ |