Commit | Line | Data |
---|---|---|
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 SBS |
6 | # Input: arg1 str file extension of files to apply changes to |
7 | # Version: 0.1.1 | |
f48d0d55 SBS |
8 | |
9 | declare fext; # file extension | |
91872e11 SBS |
10 | |
11 | list_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 |
91872e11 | 23 | main () { |
f48d0d55 SBS |
24 | # Read file extension if provided |
25 | if [[ -n "$1" ]]; then | |
26 | fext="$1"; | |
27 | fi; | |
28 | ||
91872e11 SBS |
29 | # Find the maximum number of leading digits in the filenames of working dir |
30 | max_digits="$(list_files | sed -e 's/[^0-9].*//' | awk '{ if(length > L) L=length } END { print L }')"; | |
31 | # declare -p max_digits; # debug | |
32 | ||
33 | # Loop over the files and rename them | |
34 | while read -r file; do | |
35 | re='^[0-9]+'; | |
36 | if [[ ! "$file" =~ $re ]]; then continue; fi; | |
37 | ||
38 | # Extract the leading digits | |
39 | digits="$(echo "$file" | sed 's/\([0-9]*\).*/\1/')"; | |
40 | # Zero-pad the digits | |
41 | padded_digits="$(printf "%0${max_digits}d" "$digits")"; | |
42 | # Construct the new filename | |
43 | new_file="${padded_digits}${file#${digits}}"; | |
44 | # Rename the file | |
2d366827 | 45 | if [[ "$file" == "$new_file" ]]; then continue; fi; |
91872e11 SBS |
46 | mv -n "$file" "$new_file" |
47 | # declare -p file new_file; # debug | |
48 | done < <(list_files); | |
733bcf95 | 49 | }; # main program |
91872e11 SBS |
50 | |
51 | main "$@"; | |
52 | ||
7328c729 SBS |
53 | # Author: Steven Baltakatei Sandoval |
54 | # License: GPLv3+ |