Saturday 22 June 2019

shapefile - Selecting features by attributes using ogr2ogr?


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?



Answer



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. -f "ESRI Shapefile" is not necessary because "ESRI Shapefile" is the ogr2ogr default output format;

  2. it's convenient to skip -select and use directly the -where clause when you want to select all the fields.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...