4

I want to add a new variable to an existing netcdf file which simply increases linearly with the time variable of file, that is to say, on the first time slice the variable has the number 1 everywhere, on the second timeslice it is set to 2, etc.

I know how to open the file in python or fortran and define and add the variable and write out the modified file, but I was hoping that there might be a quick and easy way to do this from the command line using nco or cdo. I also wondered if I could do it by dumping the file to CDL format with ncdump, hacking it and turning it back to netcdf with ncgen, but that seemed more longwinded and problematic than the python approach.

ClimateUnboxed
  • 7,106
  • 3
  • 41
  • 86

2 Answers2

3

For 1-D array use this

ncap2 -s 'var=array(1,1,$time)' in.nc out.nc

For multi-dimensional arrays just add that to the zero-array

ncap2 -s 'var=array(0,0,/$time,$lat,$lon/)+array(1,1,$time)' in.nc out.nc

The numeric type of the array is determined by the type of the first argument to the array function. See the manual on array() for details.

Charlie Zender
  • 5,929
  • 14
  • 19
1

I just discovered (two years after asking!) that there is also a cdo function seq that produces an incrementing timeseries. The file produced is for a single point so you then need to enlarge the field to match the target grid and finally merge with the original file:

# in the follow $n is the number of timeslices in in.nc 
cdo -f nc4 seq,1,$n seq.nc 
cdo enlarge,in.nc seq.nc seq2d.nc # enlarge to in.nc grid
cdo merge in.nc seq2d.nc out.nc   # and merge

you can pipe this all into one command in the following way:

cdo merge in.nc -enlarge,in.nc -seq,1,$n out.nc

The nco solution is great, but I think I may find this easier to remember.

ClimateUnboxed
  • 7,106
  • 3
  • 41
  • 86