5 | | ''TBD'' |
| 5 | == How can I merge hundreds of shapefiles? == |
| 6 | |
| 7 | Here's a bash script to bulk load a directory of shapefiles that have the same schema to postgis. It could obviously be made smarter, but it seems to do the trick. |
| 8 | {{{ |
| 9 | #!/bin/bash |
| 10 | |
| 11 | # let OGR create a table from one of the files |
| 12 | ogr2ogr -f Postgresql PG:"host=smoke.hobu.net" -a_srs "EPSG:26915" -nln outputlayer first_input_shape.shp -overwrite -nlt POLYGON |
| 13 | |
| 14 | # delete all the data in the table we just created (but don't delete the table) |
| 15 | ogrinfo PG:"host=smoke.hobu.net" -sql "delete from outputlayer" |
| 16 | |
| 17 | # loop through all of the shapefiles in the directory and load them |
| 18 | for i in $(ls *.shp); do |
| 19 | ogr2ogr -f Postgresql PG:"host=smoke.hobu.net" -a_srs " EPSG:26915" -nln outputlayer $i -update -append -skipfailures |
| 20 | done |
| 21 | }}} |
| 22 | |
| 23 | This Windows cmd shell example merges multiple ''*wetlands*''shapefiles in the current directory to a single {{{merged\wetlands.shp}}} (double % to put in a script, {{{%f}}} --> {{{%%f}}}): |
| 24 | {{{ |
| 25 | mkdir merged |
| 26 | for %f in (*wetland*.shp) do ( |
| 27 | (if not exist merged\wetlands.shp ogr2ogr -f "esri shapefile" merged\wetlands.shp %f) else ( |
| 28 | ogr2ogr -f "esri shapefile" -update -append merged\wetlands.shp %f |
| 29 | ) |
| 30 | ) |
| 31 | }}} |
| 32 | The trick is to use the first input to create a new shapefile, and thereafter only update and append. See the end of http://www.gdal.org/ogr/drv_shapefile.html |