25

I am writing a shapefile after some processing; however, in the final step I need to do some selection by attributes from the the shapefile.

I am using the command in a shell with the aim of using it in a Python script when it works.

ogr2ogr -f "ESRI Shapefile" -select * where ID="1" outfile.shp infile.shp

I am getting the error message:

FAILURE: 
Unable to open datasource `Downloads' with the following drivers.

What could I be doing wrong?

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
user2757128
  • 523
  • 2
  • 6
  • 9

1 Answers1

41

You miss a minus sign before where and the select is not necessary, so it should be:

ogr2ogr -where ID="1" outfile.shp infile.shp

or if you have to do more complex query on your input data:

ogr2ogr -sql "SELECT * FROM infile WHERE ID='1'" outfile.shp infile.shp

If ID is a field of Integer type, substitute ID='1' with ID=1.

Notes:

  1. If using GDAL < 2.3,-f "ESRI Shapefile" is not necessary because "ESRI Shapefile" is the ogr2ogr default output format; If using GDAL >= 2.3, the format is guessed from the extension.
  2. it's convenient to skip -select and use directly the -where clause when you want to select all the fields.
Avocado
  • 295
  • 1
  • 9
Antonio Falciano
  • 14,333
  • 2
  • 36
  • 66
  • 2
    Many thanks it works. I am using: ogr2ogr -where "ID='1'" output.shp input.shp – user2757128 Nov 14 '13 at 10:12
  • 1
    How can I use this code : ogr2ogr -sql "SELECT * FROM infile WHERE ID='1'" outfile.shp infile.shp" in python? – Shiuli Pervin Aug 11 '16 at 10:50
  • 2
    @ShiuliPervin you can use the statement in python by using os.system('''ogr2ogr ... '''). be sure to import os at the top of your python script – geoeye Aug 29 '16 at 22:08
  • 1
    @afalciano, for the statement ogr2ogr -sql "SELECT * FROM infile WHERE ID='1'" outfile.shp infile.shp instead of just ID=1 is there a way to provide a vector or a set of numbers instead, e.g. ogr2ogr -sql "SELECT * FROM infile WHERE ID IN ['1','5','29']" outfile.shp infile.shp? – h.l.m May 11 '17 at 17:16
  • @afalciano one other thing...instead of writing out another shp file, is there a way to just get the coordinates of the selected ID polygons? – h.l.m May 11 '17 at 17:19
  • 1
    @h.l.m First question: you have to type numbers as numbers, so your example should be ogr2ogr -sql "SELECT * FROM infile WHERE ID IN [1,5,29]" outfile.shp infile.shp Second question: to get the coordinates of the selected geometry without creating another shp: ogrinfo -sql "SELECT OGR_GEOMETRY FROM infile WHERE ID IN [1,5,29]" infile.shp – Antonio Falciano May 15 '17 at 08:43
  • When using the -where switch option, I needed to identify the value with single quotes instead of double quotes in order for it to work. – Justin Braaten Sep 20 '18 at 18:23
  • With GDAL 3.6 the list needs to be () not [], e.g., ogr2ogr -sql "SELECT * FROM infile WHERE OBJECTID IN (1,5,29)" – Chris Jan 26 '23 at 20:07