Date format change from mm/dd/yyyy to yyyymmdd in comma seperate line in perl

Hi All,

I have line

,A,FDRM0002,12/21/2017,,0.961751583,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

it contains date in mm/dd/yyyy format i want to change this to yyyymmdd format using perl.

What have you tried so far?

$_= system("sed", "s/\([0-9]*\)\/\([0-9]*\)\/\(....\)/\30\10\2/g", "$line"); 

$line contain the line that i am passing and posted above.

If it is known that any token that has the "/" character is always a date in "mm/dd/yyyy" format, then you could use this:

$
$ cat input_1.txt
,A,FDRM0002,12/21/2017,,0.961751583,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
$
$ perl -lne 's|(\d+)/(\d+)/(\d+)|$3$1$2|g; print' input_1.txt
,A,FDRM0002,20171221,,0.961751583,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
$
$
 

The code above will convert all such (supposedly date-like) occurrences on each line of the file. Here's another example:

$
$ cat input_2.txt
,A,FDRM0002,12/21/2017,,0.961751583,,3/31/2016,,,,,,,,,,,,,,,,,,,,,,,,10/3/2015,,,,,,,,,,,
$
$ perl -lne 's|(\d+)/(\d+)/(\d+)|$3$1$2|g; print' input_2.txt
,A,FDRM0002,20171221,,0.961751583,,2016331,,,,,,,,,,,,,,,,,,,,,,,,2015103,,,,,,,,,,,
$
$
 

If you want only the first occurrence to be changed, then remove the qualifier "g" at the end of the s/// operator.

On the other hand, if:
(a) it is known that the 4th token is the one that has the date in it, or
(b) only the 4th token is to be changed, the others are not (whether they are dates or not)
then you could do something like the following:

$
$ cat input_3.txt
,A,FDRM0002,12/21/2017,,0.961751583,,new text/image,,,,,,,,,,,,,,,,,,,,,,,,11/29/2016,,,,,,,,,,,
$
$ perl -F"," -lane '$F[3] =~ s|(\d+)/(\d+)/(\d+)|$3$1$2|; print join(",", @F)' input_3.txt
,A,FDRM0002,20171221,,0.961751583,,new text/image,,,,,,,,,,,,,,,,,,,,,,,,11/29/2016,,,,,,,,,,,
$
$
 

the code is working for me.Thanks

Can you please suggest how to achieve the format change to YYYYMMDDHHMMSS

  • Since there is no hour, minute and second information in this: "12/21/2017", what do you want to see in the "HHMMSS" portion of "YYYYMMDDHHMMSS" ?
  • Can you have dates with and without timestamps in your data file?
  • Could you post a representative sample of your data file?

I want to see current system time in HHMMSS format

date '+%H%M%S'