Insert newline before date in yyyy-mm-dd format

K

Kevin Walzer

I am parsing a text-delimited file that has been saved as a single line.
It's actually supposed to be a multiline file with a date in yyyy-mm-dd
format as the first field on each line. To correctly structure the data,
I'm trying to insert insert a newline character before all date fields
and and then split the file into an array on the newline char. The issue
I'm running into is that I can't get the substitution pattern right.

Here's my code:

my $date1="([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])";
my $date2="\n([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])";
$_ =~ s/$date1/$date2/g;

This pattern appears to correctly match the date field, but rather
simply inserting a newline in front of the date field's data it inserts
a newline and then a string literal that looks like this:

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

What I want is to replace 2012-01-01 with \n2012-01-01, and all
subsequent date fields in the file in the same fashion. Can someone
suggest a better way to do this?

Thanks,
Kevin
 
D

Dave Saville

I am parsing a text-delimited file that has been saved as a single line.
It's actually supposed to be a multiline file with a date in yyyy-mm-dd
format as the first field on each line. To correctly structure the data,
I'm trying to insert insert a newline character before all date fields
and and then split the file into an array on the newline char. The issue
I'm running into is that I can't get the substitution pattern right.

Here's my code:

my $date1="([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])";
my $date2="\n([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])";
$_ =~ s/$date1/$date2/g;

This pattern appears to correctly match the date field, but rather
simply inserting a newline in front of the date field's data it inserts
a newline and then a string literal that looks like this:

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

What I want is to replace 2012-01-01 with \n2012-01-01, and all
subsequent date fields in the file in the same fashion. Can someone
suggest a better way to do this?

It did what you told it to do :)

Try s/(\d\d\d\d-\d\d-\d\d)/\n$1/g;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top