Replace part of a matched regex with sed

Viewed 254

I have a sample text which is a database output:

objs/blabla | Restore | manual | Restore Failed: The volume does not want to exist | BackupFailed | 2020-10- 06T21:39:01 | 2020-10-06T21:39:01 | 0 | 0 | 0 > | 0 | 0

I need to change only the 'T' from the time/date string to a ',' (comma).

So far, I have tried:

sed -e 's/[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}/[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}/g' -e 's/T/,/g'

But it fails to isolate only the date time string, and produces the following output:

objs/blabla | Restore | manual | Restore Failed:,he volume does not want to exist | BackupFailed | 2020-10- 06,21:39:01 | 2020-10-06,21:39:01 | 0 | 0 | 0 > | 0

Thus, it's also changing the 'The' to ',he' which is unwanted.

2 Answers

You don't need to match full date-time string. Following sed should work for you:

sed -E 's/([0-9]{2})T([0-9]{2})/\1,\2/g' file
objs/blabla | Restore | manual | Restore Failed: The volume does not want to exist | BackupFailed | 2020-10-06,21:39:01 | 2020-10-06,21:39:01 | 0 | 0 | 0 > | 0 | 0

Details:

  • ([0-9]{2}) - Here we match 2 digits before and after T and capture them in group #1 and #2
  • \1,\2: We put captured values back with , replacing T

As per OP's comments below, more fine grained regex that worked:

sed -E 's/([0-9]{4}(-[0-9]{2}){2})T([0-9]{2}(:[0-9]{2}){2})/\1,\3/g' file

With GNU awk gensub option could you please try following.

awk -v regex="([0-9]{2})T([0-9]{2})" '{$0=gensub(regex,"\\1,\\2", "g", $0)} 1' Input_file

Explanation: Adding detailed explanation for above.

awk -v regex="([0-9]{2})T([0-9]{2})" '   ##Starting awk program from here, mentioning regex here to match 2 digits T 2 digits.
{
  $0=gensub(regex,"\\1,\\2", "g", $0)    ##using gensub to match the regex in current line and substitute 1st and 2nd matched part with comma globally in current line and save it into current line itself.
}
1                                        ##Mentioning 1 will print edited/non-edited line here.
' Input_file                             ##Mentioning Input_file name here.
Related