[GIS] How to use -where SQL in an ogr2ogr loop in GDAL/OGR (bash)

ogrshapefile

I'm using the following code:

while read line; do
for att in $line; do
ogr2ogr -where "newcode='$att'" -f "ESRI Shapefile" $OUTPUT/$att.shp $INDATA
done
done < $SCRIPT/newcodes.txt

The text file is being read correctly as shapefiles named after all names in the textfile list are being created. However, the shapefiles are empty (no attribute table or polygons). The ogr2ogr line of code works outside of the loop on a single feature within the shapefile. The newcodes.txt contains 3-5 letter codes e.g. aaa, gbe.

I think the problem is getting bash to treat $att as text to search for in the attribute table of the shapefile within the -where switch.

Any help much appreciated.

Update:

Attribute Table Sample

The shapefile has 15 columns in the table, and 6506 rows/features.

The 'newcode' field which I'am trying to read with the -where switch was joined to the table. I have tried using the loop with a pre-existing field and it still produced empty shapefiles.

Update 2:

After a bit more interrogation, I've noticed that the shapefiles are being produced with a space after their name. E.g. 'aaa .shp' rather than 'aaa.shp'. This probably means that the $att variable is being read with a space also, and therefore not matching anything in the attribute table. I have checked the text file, and there are no spaces in there. Still unsure how to fix.
enter image description here

e.g.
cdg
cdh
cdi
cej
cea
eig
fjj
fja
fjf

Best Answer

You can try to escaping the dollar sign.

ogr2ogr -where "newcode='\$att'" -f "ESRI Shapefile" $OUTPUT/$att.shp $INDATA

If that doesn't work you can try this

ogr2ogr -where 'newcode="$att"' -f "ESRI Shapefile" $OUTPUT/$att.shp $INDATA
Related Question