Naming number to months

Hi,

I have many files of monthly means from model simulation such as 1,2,3,4.....12, corresponding to jan, feb, mar,....., dec.
e.g. avg_1.nc, avg_2.nc, ............., avg_12.nc.
i want to write a shell script such that it should conveet number into months and year such as..
avg_jan_2001,avg_feb_2001,......,avg_dec_2001.

how can i do it using shell script ?

thanks

perl -npi.bak -e 'BEGIN{@mon=qw(null jan feb mar apr may jun jul aug sep oct nov dec);} s/avg_(\d).nc/avg_$mon[$1].nc/g;' monthly_means.dat 

Remove the .bak to stop creating backups when you're satisfied it works as expected.

Are you trying to rename these files then?

Well, as a starter I could suggest the case statement. Assuming that you are sh, ksh or bash it would be something like this:-

case month_num in
   1) month_name=jan ;;
   2) month_name=feb ;;
   3) month_name=mar ;;
   4) month_name=apr ;;
   5) month_name=may ;;
   6) month_name=jun ;;
   7) month_name=jul ;;
   8) month_name=aug ;;
   9) month_name=sep ;;
   10) month_name=oct ;;
   11) month_name=nov ;;
   12) month_name=dec ;;
   *) echo "Invalid month value" ;;
esac

You will need to chop out the number from the incoming file name as month_num and the afterwards, you can use $month_name as you wish.

I hope that this helps. Let us know how you get on and if you need any more guidance.

Robin
Liverpool/Blackburn
UK

Hi,

For example, I have 24 files corresponding to JAN to DEC 2001 and JAN to DEC 2002.

the files are avg_1.nc avg_2, ....... avg_24.nc.

I want to rename it as

avg_jan_2001, avg_feb_2001,...........,avg_dec_2002.nc

I am trying it for first year as...

#!/bin/sh

year_st=2001
year_en=2001
year=$year_st
while [ $year -le $year_en ]
do
 for var in jan feb mar apr may jun jul aug sep oct nov dec
   do
      echo $var_$year
     
   done
     year = $(( year_st+1 ))
 done

But it gives me only 2001 without end.

can anybody modify this script for two years ?

thanks

A few issues here:-

  • Your value for year_en is 2001 so the range is 2001 to 2001
  • You increase the value year by adding one to the value year_st , which means you could have an infinite loop if year_st does not equal year_en
  • You should really use { and } to wrap your variables when you are using them, such that your echo becomes echo ${var}_${year} Does this give you anything further to work on?



    I hope that this helps you.


    Robin