Search code examples
shellunixsedcommand

How to change date format with Sed command?


I am trying to change the date format from YYYY-MM-DD to DD/MM/YYYY in all lines of a file using the sed command.

For example:

2021-04-01 00:15,69,0,38,1,1,0,0,0,32

should be:

01-04-2021 00:15,69,0,38,1,1,0,0,0,32

I have tried the following using regular expressions:

sed -E 's,[0-9]{4}-[0-9]{2}-[0-9]{2},\3-\2-\1,g'

unfortunately this does not work and gives me an error (not defined in the RE).

it would be really great if someone could help me to solve this.


Solution

  • You forgot capturing groups with ( ):

    $ sed -E 's,^([0-9]{4})-([0-9]{2})-([0-9]{2}),\3-\2-\1,g' <<< '2021-04-01 00:15,69,0,38,1,1,0,0,0,32'
    01-04-2021 00:15,69,0,38,1,1,0,0,0,32