wiki:FAQVector

Version 3 (modified by maphew, 13 years ago) (diff)

fixed broken parenthesis in cmd example

FAQ - Vector

  1. How can I merge hundreds of shapefiles?

How can I merge hundreds of shapefiles?

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.

#!/bin/bash

# let OGR create a table from one of the files
ogr2ogr -f Postgresql PG:"host=smoke.hobu.net" -a_srs "EPSG:26915" -nln outputlayer first_input_shape.shp -overwrite -nlt POLYGON

# delete all the data in the table we just created (but don't delete the table)
ogrinfo PG:"host=smoke.hobu.net" -sql "delete  from outputlayer"

# loop through all of the shapefiles in the directory and load them
for i in $(ls *.shp); do
  ogr2ogr -f Postgresql PG:"host=smoke.hobu.net" -a_srs " EPSG:26915" -nln outputlayer $i -update -append -skipfailures
done 

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):

mkdir merged
for %f in (*wetland*.shp) do (
  if not exist merged\wetlands.shp (
      ogr2ogr -f "esri shapefile" merged\wetlands.shp %f) else (
      ogr2ogr -f "esri shapefile" -update -append merged\wetlands.shp %f -nln Wetlands )
)

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