# Count number of vertices in a shapefile using OGR

I'd like to extract the total number of vertices in a shapefile using command-line OGR.

This answer suggests a method for intersections, but it isn't clear how to cross-apply it.

Many other methods suggest writing little Python scripts, but this seems like a needlessly complex solution.

To extract the total number of vertices in a shapefile, I'd simply use a bit of Spatialite SQL:

``````ogrinfo states.shp -dialect SQLite -sql "SELECT sum(ST_NPoints(geometry)) AS n_vertices FROM states"
``````

Example of output:

``````ogrinfo states.shp -dialect SQLite -sql
"SELECT sum(ST_NPoints(geometry)) AS n_vertices FROM states"
INFO: Open of `states.shp'
using driver `ESRI Shapefile' successful.

Layer name: SELECT
Geometry: None
Feature Count: 1
Layer SRS WKT:
(unknown)
n_vertices: Integer (0.0)
OGRFeature(SELECT):0
n_vertices (Integer) = 11481
``````
• I would prefer this solution over the sed based one because a) sed and wc are not available on Windows and b) the same SQL works as well for shapefiles which contain points, lines, and polygons. – user30184 Aug 27 '17 at 19:30

I accomplished it using the following command:

``````ogrinfo -al myshapefile.shp | grep POLYGON | sed 's/\$/,/' | tr -d -c "," | wc
``````

This begins by printing the shapefile contents to stdout, including all of the geometry. (`ogrinfo -al myshapefile.shp`)

Next, we extract only the lines containing geometry (`grep POLYGON`)

This results in a list of points of the form, for a multipolygon, of:

``````(((34 43,22 10,70 5),(23 43,54 1,89 2)),((23 43,43 2)))
``````

Notice that each point is followed by a comma, except the last one.

Therefore, we add a comma to the end of the line. (`sed 's/\$/,/'`)

Finally, we eliminate every character that is not a comma (`tr -d -c ","`) and count the commas (`wc`) which gives the number of points.

• That's awesome. You really mean shapefile and you really mean command line. :) If using R was an option I would Rscript -e "x <- sf::read_sf('myshapefile.shp'); nrow(spbabel::sptable(x))" – mdsumner Aug 26 '17 at 21:58