Bash to split string and numbering it just like Python enumerate function

I think you can just add something like count=$(($count+1))

#!/bin/bash
#
# Script to split a string based on the delimiter

my_string="One;Two;Three"
my_array=($(echo $my_string | tr ";" "\n"))

#Print the split string
count=0
for i in "${my_array[@]}"
do
    count=$(($count+1))
    echo $count - $i
done

I saw you posted a post earlier today, sorry I failed to upload the code but still hope this could help you

my_string="AA-BBB"
IFS='-' read -ra my_array <<< "$my_string"
len=${#my_array[@]}
for (( i=0; i<$len; i++ )); do
    up=$(($i % 2))
    #echo $up
    if [ $up -eq 0 ]
    then 
        echo ${my_array[i]} = '"Country name"'
    elif [ $up -eq 1 ] 
    then
        echo ${my_array[i]} = '"City name"'
    fi
done

Here is a standard bash way of doing this:

my_string="One;Two;Three"

IFS=';' read -ra my_array <<< "$my_string"
# builds my_array='([0]="One" [1]="Two" [2]="Three")'

# loop through array and print index+1 with element
# ${#my_array[@]} is length of the array
for ((i=0; i<${#my_array[@]}; i++)); do
    printf '%d: %s\n' $((i+1)) "${my_array[i]}"
done
1: One
2: Two
3: Three

Tags:

Bash