Bash: smarter way to generate a sequence of digit-alphabet combination?

Viewed 80

Are there smarter ways (I am pretty sure there are) than the code below to obtain a sequence of digits with leading zero, accompanied by a alphabet starting from 'c'?

$ paste <(echo {01..10}|tr ' ' \\n) <(echo {c..l}|tr ' ' \\n) | sed 's/\t//g'
01c
02d
03e
04f
05g
06h
07i
08j
09k
10l
2 Answers

Here is one way.

#!/usr/bin/env bash

add_num(){
  local n=1
  local f

  for f; do
    printf '%02d%s\n' $((n++)) "$f"
  done
}

add_num {c..l}

The function/code above is not limited to just {c..l} it can be {a..z} or even an array.

According to help for

for: for NAME [in WORDS ... ] ; do COMMANDS; done
    Execute commands for each member in a list.
    
    The `for' loop executes a sequence of commands for each member in a
    list of items.  If `in WORDS ...;' is not present, then `in "$@"' is
    assumed.  For each element in WORDS, NAME is set to that element, and
    the COMMANDS are executed.
    
    Exit Status:
    Returns the status of the last command executed.

So the for loop inside the function the in WORDS...; is omitted. It is the same thing as for f in "$@"; do ...; done according to the help where "$@" expands to all the positional parameter, e.g. "$1", "$2", "$3" and so on.

See help printf and help local

man 1p printf (if availabe) has a more detailed explanation than help and in man bash

See also Arithmetic Expansion and Arithmetic Evaluation in man bash for the $((n++)).

If perl is your option, would you please try:

perl -e '
    $n = "01"; $a = "c";
    for (1 .. 10) {
        printf "%s%s\n", $n++, $a++;
    }
'
Related