HellishHeat
HellishHeat

Reputation: 2491

Text Editor (regex?) trick to interpret a Date String

Take this: 20120204235900

This represents: 2012 02 04 23:59:00, or 4/Feb/2012 at 23:59:00

Well I have thousands of these and would like to change them to this: 2012/02/04 23:59:00, for example.

I know I could do a Java program but there must be an easy way to do this with some text editor.

Any ideas?

Thanks in advance.

Upvotes: 2

Views: 108

Answers (3)

Boris
Boris

Reputation: 7132

You can use sed (Stream EDitor), which is normally available on any *nix system. This one liner should work:

sed -e "s/^\([0-9]\{4\}\)\([0-1][0-9]\)\([0-3][0-9]\)\([0-2][0-9]\)\([0-6][0-9]\)\([0-6][0-9]\)/\1\/\2\/\3 \4:\5:\6/g" <filename>

Upvotes: 1

stema
stema

Reputation: 93026

In Notepad++ you would be able to this:

([12]\d\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)

I check at the start for 1 or 2 to have a little bit of Date validation, if not needed then just replace [12] with \d

and replace with

\1/\2/\3 \4:\5:\6

To turn "20120204235900" into "2012 02 04 23:59:00"

The trick is to access the submatches in the brackets with the \1 (called a backreference). So the group 1 is the content of the first pair of brackets in \2 the match of the second pair of brackets.

With this, its no problem to reorder the submatches, but to replace the 02 with February a more complex logic would be needed. I think this is not possible in an editor.

Note: This is just testing for 14 digits starting with 1 or 2, so it does not verify if the digit sequence is a valid date/time!

Upvotes: 2

Petar Ivanov
Petar Ivanov

Reputation: 93060

I would use Notepad++.

Just use regex replace like this:

([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])

and replace it with

\1/\2/\3 \4:\5:\6

Upvotes: 1

Related Questions