Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

shell

cut

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.

like image 233
DoesJohnDo Avatar asked Aug 21 '13 07:08

DoesJohnDo


1 Answers

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.

like image 116
Shashilpi Avatar answered Sep 22 '22 00:09

Shashilpi