Issue
Hi can anyone suggest how to grep UTC DateTime in Linux?
I'm trying the below syntax but not working.
utcdate=$(grep '\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2]\d|3[0-1])T(?:[0-1]\d|2[0-3]):[0-5]\d:[0-5]\dZ' filename)
date format : 2021-06-22T16:15:23Z
Solution
The easiest fix is by adding -oP
options and append | head -1
to the pattern:
utcdate=$(grep -oP '\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2]\d|3[0-1])T(?:[0-1]\d|2[0-3]):[0-5]\d:[0-5]\dZ' filename | head -1)
The o
option will output the matched substring only, P
will allow the PCRE regex syntax and | head -1
to ensure you get a single match.
A POSIX pattern is also possible:
utcdate=$(grep -oE '[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])T([0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]Z' filename | head -1)
where
- All
(?:
are replaced with(
as the non-capturing groups are not supported by POSIX ERE \d
replaced with[0-9]
(as\d
is not supported by POSIX regex).
If you escape all (
, )
, {
and }
, you can remove E
as this expression will become POSIX BRE compliant, but that "escaping hell" looks ugly, IMHO.
Answered By - Wiktor Stribiżew Answer Checked By - Willingham (WPSolving Volunteer)