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

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


You can say:

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

Alternatively,

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

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; donefield1field2field3field4


Using cut is not the recommended command to do the job as it can be done in one line using awk.

For e.g.

data='field1;field2;field3;field4;'echo $data|awk -F';' '{print NF}'

Actually above will return 5 because in given data there is "semicolon" at the end, hence linux awk assumes that last field is empty.

But if this is expected to have it like this then you can use below command to subtract 1.

echo $data|awk -F';' '{print NF-1}'

Explanation:-F option in awk is for delimiter, in this case it's semicolon (enclosed in single quote)NF means Number of fields.


Pure bash solution:

myStr='field1;field2;field3;field4;'x="${myStr//[^;]}"                   # remove everything but the delimiter ';'echo "${#x}"                         # get the length - outputs 4