Assuming I want to extract the time part of a date/time string on the shell I can do something like:
echo "2021-06-10T10:42:30.016+0200" | sed 's|.*T\(.*\)\..*|\1|g'
This returns
10:42:30
How can I achieve the same with jq and sub()?
I'm missing the right syntax. I was not able to find any good examples. E.g. I've been trying:
jq '<myid> | sub(".*T(.*)\\..*"; "\1")'
jq '<myid> | sub(".*T(.*)\\..*"; "$1")'
jq '<myid> | sub(".*T\\(.*\\)\\..*"; "\1")'
But none of this returns back what I want?
In JQ we use named capture groups for that.
sub(".*T(?<x>.*)\\..*"; .x)
In this case, you may remove all up to T and all the text starting with (and including) a dot with .*T|\.[^.]*$ regex:
s='{"node":"2021-06-10T10:42:30.016+0200"}'
jq '.node |= gsub(".*T|\\.[^.]*$"; "")' <<< "$s"
Output:
{
"node": "10:42:30"
}
Pattern details:
.*T - any text and then T| - or\. - a dot[^.]* - zero or more chars other than a .$ - end of string.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With