Extracting a date from a filename and converting it in Bash

Viewed 49

I'm trying to extract the date from a filename and assign the converted date to a variable.

E.g.

Filename="SomeFilename 05 May 2022.zip"

And I want to extract 05052022 and assign that to a variable.

5 Answers

The following method is a little lengthy but you can use a bash regex for extracting the date parts and a case switch for converting the month:

#!/bin/bash

filename='SomeFilename 05 May 2022.zip'

if [[ $filename =~ ([0-9]{2})\ ([A-Z][a-z]{2})\ ([0-9]{4})\.[^.]+$ ]]
then
    d=${BASH_REMATCH[1]}

    case ${BASH_REMATCH[2]} in
    Jan) m=01;; Feb) m=02;; Mar) m=03;;
    Apr) m=04;; May) m=05;; Jun) m=06;;
    Jul) m=07;; Aug) m=08;; Sep) m=09;;
    Oct) m=10;; Nov) m=11;; Dec) m=12;;
    esac

    y=${BASH_REMATCH[3]}

    date=$d$m$y
fi

Using and (PCRE mode) + the date command:

Filename="SomeFilename 05 May 2022.zip"
date=$(grep -oP '\d{2}\s+\w+\s+\d{4}(?=\.zip)' <<< "$Filename")
res=$(date -d "$date" '+%d%m%Y')

Using sed

$ Filename="SomeFilename 05 May 2022.zip"
$ date=$(sed s"/[^ ]* \([^.]*\).*/date -d '\1' +'%d%m%Y'/e" <<< $Filename)
$ echo "$date"
05052022
Filename="Some File name 03 May 2022.txt"
$ awk -F[' .'] '{mydate=$(NF-3)$(NF-2)$(NF-1)" +%d%m%Y"; print|"date -d " mydate}' <<<"$Filename"
03052022

Unless the month names aren't fixed 3-letters wide, just a lookup string suffices

CODE

# gawk profile, created Wed May 25 03:54:41 2022
# BEGIN rule(s)

BEGIN {  _ = "[0-9 ]"
             gsub(".",(_),_)
             gsub(OFS, "",_)
        __ = _
         _ = "JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC"

    sub("[^\\]]+[]][^\\]]+[]]","& ("(_)") ",__)
               sub("9",     "3",__)
    sub(" [[][0][-][9]"," [0-2",__)
     ___="|"_
      _+=_^=_<_
} { 
     $-__=toupper($-__) 

}    gsub(__,    "\4""&\3")+\
     gsub("^[^\4]*[\4]|[\3][^\3]*$","") + \
      sub("[^0-9]+",                       \
  sprintf("%0*.f",_,(_+index(___,substr($-__,_+_++,_)))/(--_+_)))'

OUTPUT

05052022
Related