How to get the size of a string array in the shell script?

Asked

Viewed 628 times

1

I have a string that I pass as a parameter, for example :

 "2,3,4,5"

To pick up every item of it I make :

#!/bin/bash

for ((i=1; i<=4; i++))
do
        echo "$1" | cut -d "," -f $i
done

But I would like to make the loop iterate to the maximum size of the string (which is variable), where each value separated by comma is an item. So how can I count the number of items to insert into for?

Example: To "2,3,4,5" you have 4 items.

1 answer

3


Actually you don’t need the size, just use tr to exchange the comma for \n and go through the result with for:

for i in $(echo "2,3,4,5" | tr "," "\n")
do
    echo $i
done

This prints:

2
3
4
5

In fact, only the command echo "2,3,4,5" | tr "," "\n" already prints the numbers the way you need them. The for would only be necessary if you need to do something else with the numbers. If you only need to print them, one per line, you don’t even need the for.


If you also need the amount, just count the lines generated by tr, using wc (with the option -l, which returns only the number of rows):

n=$(echo "2,3,4,5" | tr "," "\n" | wc -l)

In this case, the value of $n will be 4.


PS: The syntax $( comando ) is called Command Substitution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.