November 26, 2009

Extracting bands from hdf4_eos to tif

Here is a quick and dirty bash script I wrote to extract all bands from a modis image and save each to a tiff file. The saved bands are named after the sub layer in the original hdf4 file. The script actually generates a second script called batch.sh so you can peek in there to see the undelying gdal_translate commands that are generated.

One day I need to get around to letting QGIS natively support HDF – maybe a good topic for those attending the OSGEO hackfest in NY?


#!/bin/bash
#Set field separator to linefeeds rather than spaces
echo "#!/bin/bash" > batch.sh
chmod +x batch.sh
IFS=$'\n'
for FILE in *.hdf
do
  echo $FILE
  LAYERS=$(gdalinfo $FILE | grep SUBDATASET | grep NAME  | sed 's/[A-Z0-9\_]*=//g')
  for LAYER in $LAYERS
  do
    LAYER=$(echo $LAYER | sed 's/  //g')
    NEWFILE=$(echo $LAYER | \
    sed 's/  //g' | sed 's/"//g' | sed 's/ //g'| sed 's/:/./g' ).tif
    CMD="gdal_translate -of GTiff '${LAYER}' $NEWFILE"
    echo $CMD >> batch.sh
  done
done

exec ./batch.sh