Search code examples
bashshellcut

How to get the count of fields in a delimited string?


Given the following data:

 field1;field2;field3;field4;

How to get the number of fields in this string? For example, the command should give back 4 for this case.

Actually, I don't have the same number of contents in each line, but I need to return them all anyway. Once I manage to count the number of fields, I will also manage to make a loop to get them all.


Solution

  • You can say:

    $ echo "field1;field2;field3;field4;" | grep -o ";" | wc -l
    4
    

    Alternatively,

    $ tr -dc ';' <<< "field1;field2;field3;field4;" | wc -c
    4
    

    EDIT: In order to loop over the fields, you can say:

    $ IFS=';' read -ra field <<< "field1;field2;field3;field4;"
    $ for i in "${field[@]}"; do echo $i; done
    field1
    field2
    field3
    field4