bash

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


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.


Solution

  • 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