bashradixfilesplitting

Bash compute the letter suffix from the split command (i.e. integer into base 26 with letters)


The split command produces by default a file suffix of the form "aa" "ab" ... "by" "bz"...

However in a script, I need to recover this suffix, starting from the file number as an integer (without globbing).

I wrote the following code, but maybe bash wizards here have a more concise solution?

alph="abcdefghijklmnopqrstuvwxyz"
for j in {0..100}; do
    # Convert j to the split suffix (aa ab ac ...)
    first=$(( j / 26 ))    
    sec=$(( j % 26 ))
    echo "${alph:$first:1}${alph:$sec:1}"
done

Alternatively, I could use bc with the obase variable, but it only outputs one number in case j<26.

bc <<< 'obase=26; 5'
# 05
bc <<< 'obase=26; 31'
# 01 05

Solution

  • From top of my head, depending on 97 beeing ASCII a:

    printf "\x$(printf %x $((97+j/26)))\x$(printf %x $((97+j%26)))\n"
    printf "\\$(printf %o $((97+j/26)))\\$(printf %o $((97+j%26)))\n"
    awk "BEGIN{ printf \"%c%c\\n\", $((97+j/26)), $((97+j%26))}" <&-
    printf %x $((97+j/26)) $((97+j%26)) | xxd -r -p
    

    You could also just write without temporary variables:

    echo "${alph:j/26:1}${alph:j%26:1}"
    

    In my use case, I do want to generate the full list

    awk should be fast:

    awk 'BEGIN{ for (i=0;i<=100;++i) printf "%c%c\n", 97+i/26, 97+i%26}' <&-