1

I have multiple global climate model (GCM) data files. I successfully cropped one file but it takes time to crop one by one over thousand data files manually. How can I do multiple crops? Thanks

ClimateUnboxed
  • 7,106
  • 3
  • 41
  • 86

2 Answers2

1

What you need is a loop combined with some patience... ;-)

for file in $(ls *.nc) ; do
    cdo sellonlatbox,lon1,lon2,lat1,lat2 $file ${file%???}_crop.nc 
done

the %??? chops off the ".nc" and then I add "_crop" to the output file name...

ClimateUnboxed
  • 7,106
  • 3
  • 41
  • 86
1

I know I am a little late to add to the answer, but still wanted to add my knowledge for those who would still pass through this question.

I followed the code given by Adrian Tompkins and it seems to work exceptionally fine. But there are somethings to be considered which I'd like to highlight. And because I am still novice at programming, please forgive my much limited answer. So here are my findings for the code above to work...

  1. The code used calls CDO (Climate Data Operators) which is a non-GUI standalone program that can be utilized in Linux terminal. In my case, I used it in my Windows 10 through WSL (Ubuntu 20.04 LTS). There are good videos in youtube for using WSL in youtube.

  2. The code initially did not work for until I made a slight change. The code

    for file in $(ls *.nc) ; do
          cdo sellonlatbox,lon1,lon2,lat1,lat2 $file ${file%???}_crop.nc 
    done
    

worked for me when I wrote it as

for file in $(ls *.nc) ; do
    cdo sellonlatbox,lon1,lon2,lat1,lat2 $file ${file%???}_crop.nc;
done

see the presence of a ; in the code in line 2.

  1. The entire code (in my case to work) was put in a text file (can be put as script in other formats as well) and passed as a script in the Linux terminal. The procedure to execute the script file is as follows:

3.a) create the '.txt' file containing the script above. Do note that the directory should be checked in all steps.

3.b) make the file executable by running the command line
chmod +x <name_of_the_textfile_with_extension> in the terminal.

3.c) run the script (in my case it is the textfile) by running the command line ./<name_of_the_textfile_with_extension>

The above procedures will give you cropped netcdf files for the corresponding netcdf files in the same folder.

cheers!

  • 1
    hi, nice detailed answer - note that the ";" is not needed if you have the code in a script and you hit "carriage return" to make sure the "done" is on a new line. If you cut and paste the code from the web, it may have picked it up as a continuous line. In fact from the command line you can write "for file in list ; do cdo command in out ; done" on one line, while in a script you can also put the "do" on a new line and not use semi-colon at all... – ClimateUnboxed May 13 '22 at 21:51
  • Thank You so Much Adrian! I am learning so much from people who have big and generous hearts like yours. much appreciated... – Nyigam Bole Jun 29 '22 at 07:39