Using sed to convert YYYYMMDD to YYYY-MM-DD

Using sed to convert YYYYMMDD to YYYY-MM-DD

Post by Milhouse Van Houte » Thu, 17 Nov 2005 03:43:08



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

 
 
 

Using sed to convert YYYYMMDD to YYYY-MM-DD

Post by Lars Kellogg-Stedma » Thu, 17 Nov 2005 03:56:30



Quote:> 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?

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.

Quote:> 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>

This won't match the above sed expression (which requires 8 characters
betten <date> and </date>).

-- Lars

--

This email address will expire on 2005-11-22.

 
 
 

Using sed to convert YYYYMMDD to YYYY-MM-DD

Post by Chris F.A. Johnso » Thu, 17 Nov 2005 03:54:20



Quote:> 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.

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

 
 
 

Using sed to convert YYYYMMDD to YYYY-MM-DD

Post by Milhouse Van Houte » Thu, 17 Nov 2005 04:48:21


Thanks to both of you -- works fine, and it's instructive to see the
different ways you went about it.