Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I have a file containing a long comma-delimited list of numbers, like this:

2,8,42,75,101

What's the simplest command (from a Unix shell) to get the count of numbers in this file? In the example above, that would be 5.

share|improve this question
add comment

5 Answers

up vote 4 down vote accepted

Easiest is probably to just count the commas:

sed 's/[^,]//g' yourfile.csv | wc -c

Normally you'd add one to get the number of elements, but if there's a newline there it's counted too. Convenient in this case, I guess.

Also with awk:

awk -F, '{print NF}' yourfile.csv
share|improve this answer
    
Going with this approach, with a small twist - sedding the commas to spaces then using wc -w to get the word count. –  Andrew Apr 29 '11 at 18:42
add comment

as per here: http://www.cyberciti.biz/faq/finding-bash-shell-array-length-elements/

this isnt too difficult

if you can define your list of elements in an array like so:

ArrayName=("element 1" "element 2" "element 3")

then its as simple as:

echo ${#ArrayName[@]}

however you have a csv so this may be better: http://www.thelinuxblog.com/working-with-csv-files-in-bash/

echo $(cat file.csv | sed ‘s/, /_ /g’ | tr ‘,’ ‘\n’ | wc -l)
share|improve this answer
add comment

Found this solution:

cat file.csv | sed 's/,/ /g' | wc -w
share|improve this answer
add comment

If you wanted to use python you could do:

str = given_csv_line_as_string
if str[-1] == ',': str = str[:-1]
print len(given_csv_line_as_string.split(','))

Note that this will return the correct length regardless if there is a hanging comma.

I'm sure there is something similar and more sysadmin-y in perl but I don't use perl.

share|improve this answer
add comment

Or use grep

grep -o "," | wc -l

Actually to get this correct you would need to add one to the result

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.