How can I count the number of CPU cores?

Try this,

As per man lscpu

CORE   The logical core number. A core can contain several CPUs.

SOCKET The logical socket number. A socket can contain several cores.

cores as well as sockets are physical where as CPU(s) are logical number. So to find the number of cores your system has, do number of cores x number of sockets

A sample output of lscpu is as follows :

Thread(s) per core:    2
Core(s) per socket:    8
Socket(s):             2

So the total number of cores: 16

The total number of CPU(s): 32 (Since number of threads per core is 2)

As @Durga mentioned , the nproc gives total number of CPUs.

For more , refer this answer , to get interpretation of /proc/cpuinfo refer this

I'd like to thank @Kusalananda for helping me to understand the same.

In Terminal nproc, OP: total cpu cores

If you are only interested in the sum, you can also use GNU awk:

cat /proc/cpuinfo |grep "cpu cores" | awk -F: '{ num+=$2 } END{ print "cpu cores", num }'

Edit: This is the correct answer for the OP's intention to sum the numbers of the last column. However the question about finding out how many cores (physical/virtual) are on the machine is given in the other answers to the question.