Counting number of items in a single-row CSV file?
13,358
Solution 1
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
Solution 2
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)
Related videos on Youtube
Comments
-
Eddie almost 2 years
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
. -
Eddie about 13 yearsGoing with this approach, with a small twist - sedding the commas to spaces then using wc -w to get the word count.