2

I have a large file that contains timestamps in the following format:

2018-08-22T13:06:04.442774Z

I would like to add double quotes around all the occurrences that match this specific expression. I am trying to use sed, but I don't seem to be able to find the right command. I am trying something around these lines:

sed -e s/[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}T[0-9]\{2\}:[0-9]\{2\}:[0-9]\{2\}.[0-9]\{6\}Z/"$0"/g my_file.json

and I am pretty sure that the problem is around my "replace" expression.

How should I correct the command?

Thank you in advance.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
fatoddsun
  • 251
  • 1
  • 12

2 Answers2

2

You should wrap the sed replacement command with single quotes and use & instead of $0 in the RHS to replace with the whole match:

sed 's/[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}T[0-9]\{2\}:[0-9]\{2\}:[0-9]\{2\}\.[0-9]\{6\}Z/"&"/g' file > outfile

See the online demo

Also, do not forget to escape the . char if you want to match a dot, and not any character.

You may also remove excessive escapes if you use ERE syntax:

sed -E 's/[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{6}Z/"&"/g'

If you want to change the file inline, use the -i option,

sed -i 's/[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}T[0-9]\{2\}:[0-9]\{2\}:[0-9]\{2\}\.[0-9]\{6\}Z/"&"/g' file
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

The following works:

sed 's/\([0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}T[0-9]\{2\}:[0-9]\{2\}:[0-9]\{2\}\.[0-9]\{6\}Z\)/"\1"/g' my_file.json

multiple modifications:

  • wrap command in single quotes
  • use \( and \) to create a group (referenced by '\1` in the replacement section)
  • escape the '.' and '{' and '}' characters
Chris Maes
  • 35,025
  • 12
  • 111
  • 136