7

I am new to ogr2ogr. Does anyone know if it is possible to loop through all shapefiles in a directory, clip and output them into an identical directory with a suffix "_clipped"?

I saw this similar question about converting all files in a directory. Problem here is that using this method I overwrite all my files. Using ogr2ogr to convert all shapefiles in directory?

EDIT:

I want to make a .bat script to execute the code. This is how far I've come. It works if I output to the same folders as input, but I want it to output to some other folder. The user enters a new folder name, to where the clipped files will be saved.

Here is the returned errors:
Error 1: Failed to create file .shp file
Error 4: Failed to open shapefile 'correct path'

--
set parent=%~dp0
set ogr2ogrPath="C:\Program Files\QGIS 2.16.1\bin\ogr2ogr.exe"

set /p inFolder=Enter the name of the root folder containing the shapefiles to clip:
set /p outFolder=Enter a new name for the folder to save the clipped files:
set /p xMin=Enter xMinCoord:
set /p yMin=Enter yMinCoord:
set /p xMax=Enter xMaxCoord:
set /p xMax=Enter yMaxCoord:

for /R %parent%%inFolder% %%f in (*.shp) do %ogr2ogrPath% -skipfailures -clipsrc xMin yMin xMax xMax %parent%%outFolder%\%%~nf.shp %%f

Adrian Tofting
  • 223
  • 2
  • 6

2 Answers2

14

Modifying the referenced answer, in the Windows command line:

for /R %f in (*.shp) do ogr2ogr "%~dpnf_clipped.shp" -clipsrc clipper.shp "%f"

You just add _clipped to the output. Note, this will also clip the clipping file, and work recursively, so it will also clip the shapefiles in sub-folders.

If you don't want it recursive:

for %f in (*.shp) do ogr2ogr "%~dpnf_clipped.shp" -clipsrc clipper.shp "%f"

To run it into a subfolder without changing names of the files, although it cannot create the folder, so an empty "clipped" folder needs to exist:

for %f in (*.shp) do ogr2ogr ".\clipped\%~nf.shp" -clipsrc clipper.shp "%f"

And finally for a different folder in the same path. So instead of "C:\data" to get it into "C:\clipped" you can do:

for %f in (*.shp) do ogr2ogr ".\..\clipped\%~nf.shp" -clipsrc clipper.shp "%f"

Like with the previous command, that folder needs to exist.

HeikkiVesanto
  • 16,433
  • 2
  • 46
  • 68
2

Can you use Python? You could use some for cycle. I tried to write some concept here:

import os

wd = r"c:\your\working\dir"
os.chdir = wd
list_of_files = os.listdir(wd)

file_that_clips = "path_to_shapefile_that_clips_other"

for file in list_of_files:
    if file_to_clip[-3:] == "shp":                          # If file is a shapefile
        clipped_file = file_to_clip[:-4] + "_clipped.shp"   # New name for output
        os.system("ogr2ogr -clipsrclayer " + file_that_clips + " " + clipped_file + " " + file_to_clip)    # Execute cmd order

I'm not sure about the ogr2ogr Clip statement. But you could copy there yours.

david_p
  • 1,783
  • 1
  • 19
  • 34