Question

I want to batch covert files in a directory with a program. I want news files to keep old names, apart from the new extension. To illustrate, a single conversion would go like this:

ogr2ogr -f "GeoJSON" world_borders.json world_borders.shp

(meaning, program options out-file in-file)

Now, I want to do this with all .shp files in a directory, to get .json files. How do I create a bash script like this?

I already did

for file in *.shp ; 
do ogr2ogr -f "GeoJSON" "${file}" "${file}".json; 
done

But it didnt work. Why?

Was it helpful?

Solution

Use parameter expansion to remove the extension from a file name:

#! /bin/bash
dir=$1
for file in "$dir"/*.shp ; do
    ogr2ogr -f GeoJSON "${file%.shp}".json "$file"
done

Save to ogr.sh, make executable, call with

ogr.sh /path/to/dir
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top