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.
CodePudding user response:
The following method is a little lengthy but you can use a bash regex for extracting the info 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
CodePudding user response:
Using regex and grep (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')
CodePudding user response:
Using sed
$ Filename="SomeFilename 05 May 2022.zip"
$ date=$(sed s"/[^ ]* \([^.]*\).*/date -d '\1' '%d%m%Y'/e" <<< $Filename)
$ echo "$date"
05052022