12

According to the shp2pgsql help, the options drop, append, create and prepare are mutually exclusive. So, if I want to create a table from a shape and then append multiple other shapefiles, I do something like the following, keeping a counter to indicate whether we are in create or append mode.

cnt=0
for shp in $(ls *.shp); do

if [ $cnt -eq  0 ]  ; then

   shp2pgsql -s 27700 -c $shp schema.table_name | psql -h localhost db 

else

   shp2pgsql -s 27700 -a $shp schema.table_name | psql -h localhost db 

fi
((cnt++))
done

This works, as expected, but I have often wondered if there is a simpler way?

John Powell
  • 13,649
  • 5
  • 46
  • 62

1 Answers1

5

If you are able to use ogr2ogr it will ignore create options when appending, and ignore append options when creating.

for shp in $(ls *.shp);
do
  ogr2ogr -f "PostgreSQL" PG:dbname=databasename -append -a_srs 27700 -nln schema.table_name $shp
done

Or in windows in the command line:

for /R %f in (*.shp) do ogr2ogr -f "PostgreSQL" PG:dbname=databasename -append -nln schema.table_name "%f"
HeikkiVesanto
  • 16,433
  • 2
  • 46
  • 68