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

Viewed 914

I found interesting way to split string using tr or IFS

https://linuxhandbook.com/bash-split-string/

#!/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
for i in "${my_array[@]}"
do
    echo $i
done

Output

One
Two
Three

Based on this code, would be be possible to put a number in front of the string by using Bash?

In Python, there is enumerate function to accomplish this.

number = ['One', 'Two', 'Three']

for i,j in enumerate(number, 1):
    print(f'{i} - {j}')

Output

1 - One
2 - Two
3 - Three

I belive there should be similar tricks can be done in Bash Shell probably with awk or sed, but I just can't think the solution for now.

4 Answers

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

This is a slightly modified version of @anubhava's answer.

y_string="One;Two;Three"

IFS=';' read -ra my_array <<< "$my_string"

# ${!array_name[@]} returns the indices/keys of the array
for i in "${!my_array[@]}"
do
    echo "$((i+1)) - ${my_array[i]}"
done

From the bash manual,

It is possible to obtain the keys (indices) of an array as well as the values. ${!name[@]} and ${!name[*]} expand to the indices assigned in array variable name.

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
Related