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

DoesJohnDo picture DoesJohnDo · Aug 21, 2013 · Viewed 30.9k times · Source

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.

Answer

devnull picture devnull · Aug 21, 2013

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