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
2
  • Read about capturing groups and replacement backreferences. Commented May 30, 2016 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? Commented May 30, 2016 at 10:38

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

I like your solution best because it allows me to change the order in the date.
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

3 Comments

Better option if you just want to replace - with :, which OP wants in the first place.
obviously that's what OP asked for
there's no reason to escape - and :, just use 's/-/:/g'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.