[GIS] ogr2ogr clip all shapefiles in a directory

clipgdalogr2ogrshapefile

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

Best Answer

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.