If you want to use cdo
, no need for all those loops and writing a lot of files, just use the function deltat
:
cdo deltat in.nc diff.nc
Like the python solution, this will be orders of magnitude faster than the loops you were using, and has the advantage of being a command-line one-liner.
Alternatively, and much less concise, you can difference the two series if you know the length (I show this as this technique can be useful in other contexts):
# calculate number of steps in the file:
nstep=$(cdo -s ntime in.nc)
# do difference between steps 2:n and steps 1:(n-1)
cdo sub -seltimestep,2/$nstep in.nc -seltimestep,1/`expr $nstep - 1` in.nc diff.nc
Postscript on accumulated fields!
Note that the above solutions and BOTH the python solutions posted on this page produce an output that has one timestep less than the input, i.e. THEY THROW AWAY THE FIRST TIMESTEP. In some cases, for example if you have a model flux field that is accumulated in the forecast, which seems to be the case, you don't want to discard the first timestep (as that is the accumulation from zero at the forecast start to the first step). In that case you can extract that first step and insert it on at the "front" of the file like this:
cdo mergetime -seltimestep,1 in.nc diff.nc diff_with_step1.nc
You should also ensure you do this for the python solutions too.
you can pipe the whole thing as a oneliner (sometimes piping can lead to bus errors or seg faults, these can usually be remedied using the "-L" option to enforce sequential operations).
cdo mergetime -seltimestep,1 in.nc -deltat in.nc diff_with_step1.nc
try this if you get a seg fault
cdo -L mergetime -seltimestep,1 in.nc -deltat in.nc diff_with_step1.nc
and this to guard against rounding and accuracy issues, if you have packed data (i.e. type NC_SHORT):
cdo -L -b f32 mergetime -seltimestep,1 in.nc -deltat in.nc diff_with_step1.nc