using sed in shell script

Hi all,

I have files with the following names;

afgcxa.pem4jan.rain.nc  
afgcxa.pem4feb.rain.nc    
afgcxa.pem4mar.rain.nc      
afgcxa.pem4apr.rain.nc 

I want to rename them to

afgcxa.pem4-01.jan.rain.nc  
afgcxa.pem4-02.feb.rain.nc    
afgcxa.pem4-03.mar.rain.nc      
afgcxa.pem4-04.apr.rain.nc 

I've been able to rename them as I require but only know how to do it "manually" i.e. one-by-one

mth="jan"
for file in $(ls *$mth.rain.nc); do
 mv $file $(echo $file | sed 's/'$mth'/-02.'$mth'/g')
done

The question is - how can i do this automatically so that sed reads jan, feb, mar etc? Also, how do i perform a counter i.e. 01, 02, 03?

Thanks, Muhammad.

You can use the following script

 
#!/bin/ksh
integer j=1
for i in jan feb mar apr
do
infile=`ls afgcx*|grep $i`
mv $infile afgcxa.pem4-0$j.$i.rain.nc
j=j+1
done
 
1 Like

Thanks malikshahid85!

Is there a way to print the digits as 01, 02, 03 etc instead of 1, 2, 3? I know that independently I could use printf e.g.

printf "%02d" 4
 

but how do i incorporate this in the code?

Alternatively, how can I save results of echo or printf as variable?

Thanks.

simple alternative to printf

typeset -Z2 j=1
1 Like
#!/bin/ksh
integer j=1
for i in jan feb mar apr may jun jul aug sep oct nov dec
do
  mon=$(printf "%02d" $j)
  infile=$(ls afgcx* |grep $i)
  mv $infile afgcxa.pem4-$mon.$i.rain.nc
  j=j+1
done
1 Like

wonderful - thanks everyone!