# How to prepare GrADS's .ctl file to convert grd file into .nc file in batch mode?

I have lots of grd (GrADS) file and I want to convert those data into netCDF file using cdo. The operation needs all the corresponding ctl file and I will have to prepare all these. So, my question is there any workaround for this using bash, python or R. Here is an example of ctl file:

*need to change the file name year*_rfp25.grd for each file
DSET /home/amit/climate_data/rf/year1901_rfp25.grd
TITLE Gridded rainfall
UNDEF -999.0
XDEF  135  LINEAR  66.5 0.25
YDEF  129  LINEAR  6.5 0.25
ZDEF   1 linear 1 1
* CHANGE TDEF TO 366 FOR LEAP YEARS
TDEF 365  LINEAR 1jan1901 1DY
VARS  1
rf 0 99 GRIDDED RAINFALL
ENDVARS

• Welcome to EarthScience.SE! Which information needs to be adapted in each .ctl file? Is there one file per year and the .ctl files differ only in line 2 (filename of grd file) and 9 (start date)? – daniel.heydebreck Aug 23 '17 at 11:10
• @daniel.neumann you are right. Year and total number of days 365 /366 need to be adapted in each .ctl file – Amit Ghosh Aug 23 '17 at 11:54

After some trial n error I figured it out using the following shell script

#!/bin/bash

day_number () {
year=$1 leap="false" if [$((year % 4)) -ne 0 ] ; then
:
elif [ $((year % 400)) -eq 0 ] ; then leap="true" elif [$((year % 100)) -eq 0 ] ; then
:
else

leap="true"
fi
if [ "$leap" == "true" ]; then echo 366 else echo 365 fi } for j in {1901..2015}; do days=$(day_number j)
echo "DSET /home/amit/climate_data/rf/year${j}_rfp25.grd TITLE Gridded rainfall UNDEF -999.0 XDEF 135 LINEAR 66.5 0.25 YDEF 129 LINEAR 6.5 0.25 ZDEF 1 linear 1 1 * CHANGE TDEF TO 366 FOR LEAP YEARS TDEF${days}  LINEAR 1jan${j} 1DY VARS 1 rf 0 99 GRIDDED RAINFALL ENDVARS">year${j}_rfp25.ctl
done