Discussion:
Using sed to convert YYYYMMDD to YYYY-MM-DD
(too old to reply)
Milhouse Van Houten
2005-11-15 18:43:08 UTC
Permalink
I use an application which generates .xml files containing <date> lines
formatted like:

<date>20050911</date>

What I'd like to do is make them more readable by adding dashes like:

<date>2005-09-11</date>

That should be a one-liner in sed, but I'm new to it and can't make it work.
Anyone know how?

The only additional factor I have is that occasionally there are also <date>
lines like this, which I want ignored (of course):

<date>1997</date>

All lines that aren't <date> lines should also be ignored.

Thanks for any help
Lars Kellogg-Stedman
2005-11-15 18:56:30 UTC
Permalink
Post by Milhouse Van Houten
I use an application which generates .xml files containing <date> lines
<date>20050911</date>
<date>2005-09-11</date>
That should be a one-liner in sed, but I'm new to it and can't make it work.
Anyone know how?
This is simplistic but will work:

sed 's%<date>\(....\)\(..\)\(..\)</date>%<date>\1-\2-\3</date>%'

This just looks for (a group of four characters) (a group of two
characters) (a group of two characters), and insert dashes between them.
Post by Milhouse Van Houten
The only additional factor I have is that occasionally there are also <date>
<date>1997</date>
This won't match the above sed expression (which requires 8 characters
betten <date> and </date>).

-- Lars
--
Lars Kellogg-Stedman <***@jetable.org>
This email address will expire on 2005-11-22.
Chris F.A. Johnson
2005-11-15 18:54:20 UTC
Permalink
Post by Milhouse Van Houten
I use an application which generates .xml files containing <date> lines
<date>20050911</date>
<date>2005-09-11</date>
That should be a one-liner in sed, but I'm new to it and can't make it work.
Anyone know how?
The only additional factor I have is that occasionally there are also <date>
<date>1997</date>
All lines that aren't <date> lines should also be ignored.
sed '/<date>/ s/\([0-9][0-9][0-9][0-9]\)\([0-9][0-9]\)\([0-9][0-9]\)/\1-\2-\3/'
--
Chris F.A. Johnson, author | <http://cfaj.freeshell.org>
Shell Scripting Recipes: | My code in this post, if any,
A Problem-Solution Approach | is released under the
2005, Apress | GNU General Public Licence
Milhouse Van Houten
2005-11-15 19:48:21 UTC
Permalink
Thanks to both of you -- works fine, and it's instructive to see the
different ways you went about it.

Loading...