2

The following is text file myfile.txt

7022122465,0,0,day,2015-09-29 10:48:33
7022597642,0,0,day,2015-09-29 10:48:33
7022848906,0,0,day,2015-09-29 10:48:33
7022191546,0,0,day,2015-09-29 10:48:33
7022180761,0,0,day,2015-09-29 10:48:33
7022125589,0,0,day,2015-09-29 10:48:33
7022224472,0,0,day,2015-09-29 10:48:33

I want to change last column date format from 2015-09-29 to 2015:09:29 using regular expression please help me.

I have tried like this but replacing regular expression (i am beginner to linux)

sed -r  's/([0-9]{4}-[0-9]{2}-[0-9]{2})/([0-9]{2}:[0-9]{2}:[0-9]{2})/g' myfile.txt
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Read about [*capturing groups*](http://www.regular-expressions.info/brackets.html) and [*replacement backreferences*](http://www.regular-expressions.info/replacebackref.html). – Wiktor Stribiżew May 30 '16 at 10:22
  • 1
    @narasimharao - Please confirm if you will get data always in this format. What if you get `-` anywhere else? Are you sure that it will never happen? – Utsav May 30 '16 at 10:38

2 Answers2

3

You can use this

sed -r 's/([0-9]{4})-([0-9]{2})-([0-9]{2})/\1:\2:\3/g' myfile.txt

() are capturing groups. Whatever results are matched using capturing groups are stored and can be backreferenced during substitution using \1, \2 etc.

([0-9]{4})-([0-9]{2})-([0-9]{2})
<--------> <--------> <-------->
1st group  2nd group  3rd group
rock321987
  • 10,942
  • 1
  • 30
  • 43
3

Rather than grouping, You should try :

sed 's/-/:/g' myfile.txt

if you want to edit file in place use i option like : sed -i 's/-/:/g' myfile.txt

Rahul
  • 402
  • 2
  • 9
  • 23