Bash Scripting with date format conversion

I have a script below and wanted to change the output into three different file format (3 separate script)

#!bin/bash
#input file format postwrf_d01_20131206_0600_f08400.grb2
#postwrf_d01_YYYYMMDD_ZZZZ_f0HHHH.grb2
#zzzz= 0000,0600,1200,1800 (in UTC)
#HHHH=00000,00600,01200,01800 ..ect (in hours)

for i in postwrf_d01_*_??00_f?????.grb2; do ./wgrib2 $i -match ':((U|V)GRD:10 m above ground|PRMSL|(ABSV|HGT):(850|700) mb)|((UGRD|VGRD) 850|700|500) mb):' -grib `basename -s .gr2 $i`_subset.grb2; done

I wanted to change the current output file format to

  1. d01_YYYYMMDD_ZZZZ_f0HHHH.grb2
  2. YYYYMMDD_ZZZZ_f0HHHH.gr2
  3. nwp.TC23.YYYYMMDDZZ.f0MMMM
    # for 3, hours is converted to minutes such that 0HHHH became 0MMMM
    Y = year
    M= month
    D = Day
    Z= initialization (0000,0600,1200,1800)
    M= minutes (i.e 00000,00360, 00720 etc...)

So you you want to make a filename conversion like this:

INPUT    : postwrf_d01_YYYYMMDD_ZZZZ_f0HHHH.grb2
OUTPUT 1 :         d01_YYYYMMDD_ZZZZ_f0HHHH.grb2
OUTPUT 2 :             YYYYMMDD_ZZZZ_f0HHHH.gr2 
OUTPUT 3 :    nwp.TC23.YYYYMMDDZZ.f0MMMM

I suggest you capture the wanted subgroups e. g. with sed and then reassemble the string for the different needs.

#!/bin/bash
FILENAME="postwrf_d01_20160527_0600_f01000.grb2"
set $( echo "$filename"  \
   | sed -r -e 's/^postwrf_d01_([0-9]{4})([0-9]{2})([0-9]{2})_([0-9]{4})_f0([0-9]{4}).grb2$/\1 \2 \3 \4 \5/'  )
YYYY="$1"
MM="$2"
DD="$3"
ZZZZ="$4"
HHHH="$5"

OUTPUT_1= "d01_${YYYY}${MM}${DD}_${ZZZZ}_f0${HHHH}.grb2"

# Now calculate the hour to minutes with the (( )) function. (See man bash for arithmetic evaluation).
((MINUTES=....))
# For leading zeros you may need to use printf. 
MINUTES=$(printf "%04d" $MINUTES)
1 Like