LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Count Values in a field (https://www.linuxquestions.org/questions/linux-newbie-8/count-values-in-a-field-4175426359/)

sunveer 09-09-2012 08:10 AM

Count Values in a field
 
I have to count the number of values in a field of a file.

for eg. if there is a line in a file

abc:xyz:d

then, I want to the count the number of values in second field. The result must be therefore 3.

414N 09-09-2012 08:59 AM

I guess this thread should go into the programming subsection.
In what language are you trying to do it?
Have you assembled something till now?

sunveer 09-10-2012 12:52 AM

Quote:

Originally Posted by 414N (Post 4776146)
I guess this thread should go into the programming subsection.
In what language are you trying to do it?
Have you assembled something till now?

I want a command to do that like awk performs certain manipulations. I think awk will do but don't know how to get it work for this.

David the H. 09-10-2012 01:19 AM

So you simply want the total number of characters in the second field on each line?

There are many ways to do something like this, and it might help if you gave us some context to work with. i.e. is this for use in a larger script? If so, show the code you have already so we can help with an integrated solution.

But to give you a simple awk version:

Code:

awk -F: '{ print length( $2 ) }' infile.txt
http://www.gnu.org/software/gawk/man...-Functions.htm

If you need something more complex, you'll have to provide more details.


Here are a few useful awk references:
http://www.grymoire.com/Unix/Awk.html
http://www.gnu.org/software/gawk/man...ode/index.html
http://www.pement.org/awk/awk1line.txt
http://www.catonmat.net/blog/awk-one...ined-part-one/

colucix 09-10-2012 05:07 AM

Another suggestion using bash only. This assumes all lines in the file have the same format as mentioned (multiple fields separated by colon):
Code:

while IFS=":" read one two other; do echo ${#two}; done < filename
Inside the loop you can put everything you need to process the retrieved value. Obviously this strongly depends on your requirement and which is the scripting language that fits it at best.


All times are GMT -5. The time now is 12:06 PM.