简体   繁体   English

使用awk或sed在文件的第一列中添加增量日期

[英]add incremental date in first column of the file using awk or sed

I want to add date in the first column of the file which starts from "1950/01/01" (format : %m/%d/%Y) and date should increment with each row using awk or sed. 我想在文件的第一列(从“ 1950/01/01”开始)中添加日期(格式:%m /%d /%Y),并且日期应使用awk或sed在每一行中递增。 When adding date, leap year also needs to be considered .. 添加日期时,还需要考虑leap年

File contents are: 文件内容为:

1,2,3,4
3,4,5,6
4,7,8,9

Expected output: 预期产量:

1950/01/01,1,2,3,4
1950/02/01,3,4,5,6
1950/03/01,4,7,8,9

So far I have manage to add formatted date in the first column but not able to increment it with every row. 到目前为止,我已经设法在第一列中添加了格式化日期,但无法在每一行中增加它。

awk -v date="$(date -d '1950/01/01' '+%m/%d/%Y')" -F"," 'BEGIN { OFS = "," }  ; {print date, $0}' inout.csv 

Using Gawk 使用Gawk

Input 输入

$ cat file
1,2,3,4
3,4,5,6
4,7,8,9

Output 产量

$ awk -v date="$( date -d '1950/01/01' '+%s' )" '{print strftime("%Y/%d/%m",date)","$0; date+=86400}' file
1950/01/01,1,2,3,4
1950/02/01,3,4,5,6
1950/03/01,4,7,8,9

Explanation 说明

 awk -v date="$( date -d '1950/01/01' '+%s' )" '{ # call awk set var date with timestamp

        print strftime("%Y/%d/%m",date) "," $0;   # print date, sep comma and current line 
        date+=86400                               # one day = 86400 seconds, just increment
 }
 ' file

Alternatively with bash and GNU date: 或者使用bash和GNU日期:

a=1950/01/01
while IFS= read -r line; do echo "$a,$line"; a=$(date +%Y/%m/%d -d "$a 1 day"); done < file

Output: 输出:

1950/01/01,1,2,3,4
1950/01/02,3,4,5,6
1950/01/03,4,7,8,9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM