Saturday, 4 November 2017

gdal - gdalwarp in a bash shell for loop



I would like mask several images in bash shell, gdalwarp works for me as a simple single line command:


gdalwarp -cutline mask.shp -cwhere 'kepnev="a.tif"' -crop_to_cutline a.tif a_masked.tif 

..but it dosen't work with for loop:


for kep in *.tif;do
gdalwarp -cutline mask.shp -cwhere 'kepnev="$kep"' -crop_to_cutline $kep ${kep/.tif}_masked.tif;done

Please help. What am I doing wrong?



Answer



It's because the $kep variable in the where filter is wrapped in quotes. You need to wrap it again in single quotes:



gdalwarp -cutline mask.shp -cwhere 'kepnev="'$kep'"' -crop_to_cutline $kep ${kep/.tif}_masked.tif;done

When I run with echo, I get this output, which looks good to me:


gdalwarp -cutline mask.shp -cwhere kepnev="res_highpass.tif" -crop_to_cutline res_highpass.tif res_highpass_masked.tif
gdalwarp -cutline mask.shp -cwhere kepnev="res_highpass2.tif" -crop_to_cutline res_highpass2.tif res_highpass2_masked.tif
gdalwarp -cutline mask.shp -cwhere kepnev="res_highpass3.tif" -crop_to_cutline res_highpass3.tif res_highpass3_masked.tif
gdalwarp -cutline mask.shp -cwhere kepnev="sj00dsm.tif" -crop_to_cutline sj00dsm.tif sj00dsm_masked.tif

Addendum


Actually, i got my quotes slightly wrong because you may need to wrap the entire where clause in single quotes. After a bit of educated guessing, I've come up with this:



gdalwarp -cutline mask.shp -cwhere "'"kepnev='"'$kep'"'"'" -crop_to_cutline $kep ${kep/.tif}_masked.tif;done

Which gives me this:


gdalwarp -cutline mask.shp -cwhere 'kepnev="sj00dsm.tif"' -crop_to_cutline sj00dsm.tif sj00dsm_masked.tif

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...