Suppose you have a sea surface temperature (SST) dataset, and you want to calculate the area between two contours. In the following example, the area is calculated for SSTs in the temperature range of 5-11 °C.
ncap2 -h -O -s
Define a variable "var1", which is a mask of 1s and 0s for gridboxes where the SST is in the specified range ( 1 for yes, 0 for no ). The "ram_delete(var1@add_offset);ram_delete(var1@scale_factor)" was done because the input data set, hadisst.nc (the SST component of the United Kingdom Meteorological Office 1-degree latitude-longitude resolution global SST and ice analysis), is written as integers, and version 4.0.x ncap2 propagates the add_offset and scale_factor attributes to the floating point var1 variable, which messes up later aspects of the calculation. The output file of this calculation, "temp.nc", contains both the SST and mask variable, "var1".
ncap2 -h -O -s 'area=cos(lat*3.1415/180)*12364' out.nc
Add a variable, "area," which is the area in km2 of each gridbox of this
1-degree latitude-longitude resolution dataset. The "12364" is
appropriate to a 1-degree latitude-longitude resolution dataset:
dx = 2 * pi * earth_radius * cos(latitude*pi/180) * longitude_span_of_each_gridbox / 360
dy = 2 * pi * earth_radius * latitude_span_of_each_gridbox / 360
darea = dx * dy = 12364
Check your result with 4 * pi * earth_radius * earth_radius
ncap2 -h -O -s 'var1=var1*area' out.nc out.nc
Multiply the mask and the area variables, and save as "var1."
ncks -h -O -v var1,time,lat,lon out.nc out.nc
Rewrite the file to save only var1, and the time,lat,lon variables that are used to define it.
ncwa -h -O -N -a lat,lon out.nc out.nc
Sum "var1" over latitudes and longitudes.