Site menu:

Cyclocross For Roadies: How and Why to Get Started - Buy Now!

Site search

Categories

Merge Subdirectories of Shapefiles Using OGR

As a follow-up to my post “Merge A Directory of Shapefiles Using OGR,” I came across a similar problem today.  I had a bunch of data in subfolders inside a parent folder.  I wanted to merge all of these shapefiles into one, without manually moving them into a single directory (and since they all had the same name, that would also require renaming them all).  The technique discussed in my previous post needed a very minor tweak to make things work perfectly.  Here it is:

mkdir merged
for /R %f in (*.shp) do (
if not exist merged\merged.shp (
ogr2ogr -f “esri shapefile” merged\merged.shp %f) else (
ogr2ogr -f “esri shapefile” -update -append merged\merged.shp %f -nln Merged )
)

That’s it!  That little “/R” makes it recursively pump through all subdirectories!  Magic :)

Comments

Comment from Harry Gibson
Time February 17, 2011 at 8:33 am

Just thought i’d share a slight extension to this I’ve used to merge multiple different shapefiles across multiple different subfolders – each subfolder contains numerous shapefiles, the naming of which is identical across the folders. This will be familiar to users in the UK trying to merge data from the OS Opendata service – I used it to import the Vectormap District data into single national files:

for %I in (D:\data\SP\SP57\*.shp) do (
for /R %f in (%~nxI) do (
if not exist C:\VectorMapMerged\%~nxI (
ogr2ogr -f “esri shapefile” C:\VectorMapMerged\%~nxI %f
) else (
ogr2ogr -f “esri shapefile” -update -append C:\VectorMapMerged\%~nxI %f
)
)
)

There’s two nested for loops. The first one gets all the filenames that each directory will contain. Make sure you pick a directory where every filename is represented. It doesn’t matter if some other directories don’t contain all the files, these will skip.

The other difference is the %~nxI notation. This turns a full pathname, which the first For statement returns, into just the filename, which the other bits need.

I used this for a full set of the OS VectorMap District, one DVD worth at a time, then merged each DVD’s files manually.

Comment from darrencope
Time February 18, 2011 at 11:27 am

Harry,

Thanks for the great comment! Looks very useful!

Write a comment





Bookshelf 2.0 developed by revood.com

More in GIS (26 of 33 articles)


Here's something that may seem obvious to power users of GDAL/OGR, but not to those that are just new to ...