narasimharao vayala narasimharao vayala - 1 year ago 149
Linux Question

How to change date format in text file linux/unix

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

Answer Source

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.

<--------> <--------> <-------->
1st group  2nd group  3rd group
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download