#!/bin/bash
#A small bash script to extract the value of a variable from a netcdf file.
#Author: David Dickinson

#Define a function which gets names variables
function getncdat(){
#Note this just returns all variable data as a long list, doesn't deal with multiple species etc.
#Something like http://superuser.com/questions/396536/how-to-keep-only-every-nth-line-of-a-file might be helpful for
#multiple species. We could loop over nspec (passed as variable) and print every nspec'th line with a moving offset
#this would then (possibly) return nspec datasets although in capturing the output we might lose this, but then at least
#we've grouped all the related data together so that all that remains is to split the list at defined points.

#Can only do one variable at a time
    local FNAME=${1}
    local DATNAME=${2}
#Here we ignore the first two args and then copy
#any extra args into OPTS
    shift 2
    local OPTS=${@:-""}

#The following command is doing
#1. Use ncdump to print variable data (also prints header)
#2. Strip all lines before data: (strips header)
#3. Put everything on a single line
#4. Put a new line at the first =
#5. Ignore the first line (which contains everything up to the = sign)
#6. Delete the ";" at the end of the data
#7. Replace all , with \n so that each value ends up on a new line
#8. Delete all spaces.
    echo $( ncdump -v ${DATNAME} ${FNAME} ${OPTS} | sed -n -e "/data:/,/;/p" | tr -d "\n" | tr "=" "\n" | tail -n+2 | tr -d ";" | tr "," "\n" | tr -d " " )
}

#Copy required args
FILE=${1} 
VAR=${2}

#Ignore first two args now
shift 2

#Call function, pass any extra args at end
getncdat ${FILE} ${VAR} ${@}

