1

I'm trying to use gdalsrsinfo to get the proj4 string from a .shp and then pass it to ogr2ogr for use in a batch reprojection loop. It's close to working, but the single quotes are getting passed to the ogr2ogr command and I can't figure out how to strip them off:

My script:

        #!/bin/bash
for f in *.shp; do 
    projsrs=$(gdalsrsinfo -o proj4 $f)
    ogr2ogr -f "ESRI Shapefile" -s_srs "$projsrs" -t_srs EPSG:3857 ${f%}3857.shp $f
done

running the gdalsrsinfo command by itself returns:

username:shpfrm username$ gdalsrsinfo -o proj4 filename.shp
'+proj=utm +zone=11 +datum=WGS84 +units=m +no_defs '

When I use bash -x to test the output, I see that ''\' is at the beginning of the string and \''' is on the end.

+ for f in '*.shp'
++ gdalsrsinfo -o proj4 filename.shp
+ projsrs=''\''+proj=utm +zone=11 +datum=WGS84 +units=m +no_defs '\'''
+ ogr2ogr -f 'ESRI Shapefile' -s_srs ''\''+proj=utm +zone=11 +datum=WGS84 +units=m +no_defs '\''' -t_srs EPSG:3857 filename.shp3857.shp PC_Sec05_Frm64.shp
Failed to process SRS definition: '+proj=utm +zone=11 +datum=WGS84 +units=m +no_defs '

what I need is:

ogr2ogr -f 'ESRI Shapefile' -s_srs '+proj=utm +zone=11 +datum=WGS84 +units=m +no_defs ' -t_srs EPSG:3857 filename.shp3857.shp filename.shp
jamierob
  • 127
  • 2
  • 7
  • 2
    This means that `gdalsrsinfo -o proj4 filename.shp` outputs literal single quotes. No characters are being added by anything. For why strings with single quotes aren't being interpreted as bash code, see [this question](https://stackoverflow.com/questions/12136948/why-does-shell-ignore-quotes-in-arguments-passed-to-it-through-variables). – that other guy Oct 05 '18 at 18:39
  • It's not clear what exactly you're trying to do. For example, what's wrong with `projsrs=$(gdalsrsinfo -o proj4 $f); ogr2ogr -f "ESRI Shapefile" -s_srs "$projsrs" -t_srs EPSG:3857 ${f%}3857.shp $f`? – melpomene Oct 05 '18 at 22:12
  • that was getting really confusing. updated and simplified for clarity. still getting the extra escaped single quotes when i put the variable in double quotes. – jamierob Oct 05 '18 at 22:25
  • Without seeing the raw output from `gdalsrsinfo` there's not much to say. This looks like it should be fine, though you should quote wherever you're using `$f` and I'm not sure what you're doing with `${f%}` – miken32 Oct 05 '18 at 22:29

1 Answers1

2

You haven't shown the output from the command, but if it does have stray quotes that you don't want, you could just remove them. Reference: http://wiki.bash-hackers.org/syntax/pe#search_and_replace

#!/bin/bash
for f in *.shp; do 
    projsrs=$(gdalsrsinfo -o proj4 "$f")
    ogr2ogr -f "ESRI Shapefile" -s_srs "${projsrs//\'/}" -t_srs "EPSG:3857" "${f}3857.shp" "$f"
done

Also, you should always quote filenames, as they can contain spaces.

miken32
  • 42,008
  • 16
  • 111
  • 154
  • This worked perfectly. I need to learn a lot more about that replacement you did--thanks for the link to the resource. – jamierob Oct 05 '18 at 22:55