1

I have a file with records in this format :

D20200826,S2927,977,1

Expected output :

D20200819,S2927,977,1

Now what I am trying to achieve is if somehow I can get the date (first column) to be moved 7 days in the past, i.e. if current date is 29, I want it to be 22.

1
  • Use the date command. Commented Aug 29, 2020 at 5:43

2 Answers 2

1

Assuming your awk has time-related functions mktime() and strftime() (mawk or GNU awk), then the awk script

BEGIN {
        OFS = FS = ","
}

{
        t = mktime(sprintf("%4d %.2d %.2d 00 00 00",
                substr($1,2,4),
                substr($1,6,2),
                substr($1,8,2)));

        $1 = substr($1,1,1) strftime("%Y%m%d", t - 7*24*60*60)

        print
}

would break apart the date specification in the first comma-delimited column using multiple calls to substr() and create a Unix timestamp with mktime().

It would then decrease the generated timestamp by exactly seven days (in seconds) and re-format it as a YYYYMMDD date string using strftime(). The generated date string, along with the first character of the first column's data (a D in the example) is then assigned to the first column before the whole modified line is printed.

Testing the above script on some data:

$ cat file
D20200826,S2927,977,1
D20200106,S2927,977,1
$ awk -f script.awk file
D20200819,S2927,977,1
D20191230,S2927,977,1

A slightly shorter variant:

BEGIN { OFS = FS = "," }

{
        $1 = substr($1,1,1) strftime("%Y%m%d",
                mktime(sprintf("%4d %.2d %.2d 00 00 00",
                        substr($1,2,4),
                        substr($1,6,2),
                        substr($1,8,2))) - 7*24*60*60)
}

1

And, as a "one-liner":

awk -F, '{ $1 = substr($1,1,1) strftime("%Y%m%d",mktime(sprintf("%4d %.2d %.2d 00 00 00",substr($1,2,4),substr($1,6,2),substr($1,8,2)))-7*24*60*60) }; 1' OFS="," file
1
  • Is it possible to modify future dates only in this file ? Basically I have many records in file with current date and future dates. So if possible can only records having future dates change to 7 days before ? D20200908,S2927,977,1 D20200908,S2927,977,1 D20200908,S2927,977,1 D20201108,S2927,977,1 D20201108,S2927,977,1 I would want only the last 2 records get changed to D20201101,S2927,977,1. If that's something achievable Commented Sep 8, 2020 at 7:39
0

Only for gawk

awk -F, '{$1 = strftime("D%Y%m%d",\
mktime(gensub(/.(.{4})(.{2})(.{2})/, "\\1 \\2 \\3 0 0 0", 1, $1))-7*3600*24)}1' OFS=, file
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .