Jorge Y. C. Rodriguez
Jorge Y. C. Rodriguez

Reputation: 3449

Format date string using gawk?

I have an issue that when running this code:

gawk 'BEGIN{FS=";";RS="\r\n"}
        {
            for (i = 1; i <= NF; i++) {
                if(match($i, /([0-9]{4})-([0-9]{2})-([0-9]{2})-([0-9]{2})\.([0-9]{2})\.([0-9]{2})\.([0-9]{6})/, m)){
                    $i =  m[1]"-"m[2]"-"m[3]" " m[4]":"m[5]":"m[6]
                    printf $0 "\n"
                }

            }
        }' contact20.txt > cleaned.txt

with input:

3;0952;2001-03-22-11.56.13.514119;2;2014-09-21-10.25.58.918626;J;2015-12-27-14.17.45.593190;N;0;0001-01-01-00.00.00.000000;N;2014-09-21-10.25.58.918626;2012-11-03-21.52.55.270989;N;0001-01-01-00.00.00.000000

I get:

3 0952 2001-03-22 11:56:13 2 2014-09-21-10.25.58.918626 J 2015-12-27-14.17.45.593190 N 0 0001-01-01-00.00.00.000000 N 2014-09-21-10.25.58.918626 2012-11-03-21.52.55.270989 N 0001-01-01-00.00.00.000000

But the result should look like this:

3;0952;2001-03-22 11:56:13;2;2014-09-21 10:25:58;J;2015-12-27 14:17:45;N;0;0001-01-01 00:00:00;N;2014-09-21 10:25:58;2012-11-03 21:52:55;N;0001-01-01 00:00:00

I can't figure out why is removing the ; from the string and also is ignoring date strings like 0001-01-01-00.00.00.000000 and the match is only matching the first one?

What do I need to change to make work property?

Upvotes: 1

Views: 80

Answers (2)

Ed Morton
Ed Morton

Reputation: 203807

You don't need a loop for that, all you need is:

$ gawk '{print gensub(/([0-9]{4})-([0-9]{2})-([0-9]{2})-([0-9]{2})\.([0-9]{2})\.([0-9]{2})\.([0-9]{6})/,"\\1-\\2-\\3 \\4:\\5:\\6","g")}' file
3;0952;2001-03-22 11:56:13;2;2014-09-21 10:25:58;J;2015-12-27 14:17:45;N;0;0001-01-01 00:00:00;N;2014-09-21 10:25:58;2012-11-03 21:52:55;N;0001-01-01 00:00:00

which of course could just as easily be done with sed:

$ sed -E 's/([0-9]{4})-([0-9]{2})-([0-9]{2})-([0-9]{2})\.([0-9]{2})\.([0-9]{2})\.([0-9]{6})/\1-\2-\3 \4:\5:\6/g' file
3;0952;2001-03-22 11:56:13;2;2014-09-21 10:25:58;J;2015-12-27 14:17:45;N;0;0001-01-01 00:00:00;N;2014-09-21 10:25:58;2012-11-03 21:52:55;N;0001-01-01 00:00:00

The above uses GNU awk for gensub() and GNU or OSX sed for -E.

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Your current approach will output/repeat the same line for each field in loop.
To get the desired result as a line with transformed "date" values use the following:

awk 'BEGIN{ FS=OFS=";" }
     {  for (i = 1; i <= NF; i++) {
            if(match($i, /([0-9]{4})-([0-9]{2})-([0-9]{2})-([0-9]{2})\.([0-9]{2})\.([0-9]{2})\.([0-9]{6})/, m)){
                $i =  m[1]"-"m[2]"-"m[3]" " m[4]":"m[5]":"m[6]                                      
            }
        }
     }1' contact20.txt > cleaned.txt

cat cleaned.txt
3;0952;2001-03-22 11:56:13;2;2014-09-21 10:25:58;J;2015-12-27 14:17:45;N;0;0001-01-01 00:00:00;N;2014-09-21 10:25:58;2012-11-03 21:52:55;N;0001-01-01 00:00:00

Upvotes: 1

Related Questions