How to get the number of fields in a separation line?

Given the following data:

field1;field2;field3;field4; 

How to get the number of fields in this row? For example, the command should return 4 for this case.

In fact, I do not have the same amount of content on each line, but I still need to return them. As soon as I can count the number of fields, I will also be able to create a loop to get them all.

+6
source share
5 answers

You can say:

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

As an alternative,

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

EDIT: To iterate 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 
+9
source

Using cut is not a recommended command to do the job, as it can be done on a single line using awk.

For instance,

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

In fact, 5 will return above, because there is a semicolon in the data at the end, so linux awk assumes the last field is empty.

But if it is expected to be so, then you can use the command below to subtract 1.

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

Explanation: The -F option in awk is for a separator, in which case a semicolon (enclosed in a single quotation mark) NF means the number of fields.

+6
source

Pure bash solution:

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

The option I provided is still saved without error or manipulation.

 j=0 i=1 while [ "$j" ] do j="$(cat dataFile.txt | cut -d[delimiter] -f$i)" i="$(($i+1))" done echo "$(($i-2))" 

I initialize the variable $j to hold the results, and as long as the results exist, the loop counts each run. cut always runs over 2 fields, explaining my $(($i-2)) operator.

Put the data file separator after cutting -d. I used a comma to separate my fields, so my actual code is: cut -d, -f $ i

Hope this makes sense.

0
source
 #!/bin/bash DATA="field1;field2;field3;field4;" # save IFS OLDIFS=$IFS # set new IFS IFS=";" # set DATA as position parameters set -- ${DATA//\*/\\*} # simply get parameter count echo "Fields: $#" # restore IFS IFS=$OLDIFS 
-1
source

Source: https://habr.com/ru/post/952177/


All Articles