如何使用unix将2017年1月23日转换为2017年1日23日的csv文件行



我想知道如何将csv文件行中的所有日期转换成这种格式?示例我想将2017年1月23日转换为2017年1日23日

我使用unix

谢谢

我的文件是这样的:

2017年1月23日2018年8月17日1/1/22003年5月6日2019年5月18日

我想要这个:

2017年1月23日2018年8月17日2002年1月1日2003年6月5日2019年5月18日

我使用date_samples.csv作为我的测试数据:

23/1/17,17/08/18,1/1/02,5/6/03,18/05/2019

cat date_samples.csv | tr "," "n" | awk 'BEGIN{FS=OFS="/"}{print $2,$1,$3}' | 
while read CMD; do
date -d $CMD +%d/%m/%Y >> temp
done; cat temp | tr "n" "," > converted_dates.csv ; rm temp; truncate -s-1 converted_dates.csv

输出:

23/01/2017,17/08/2018,01/01/2002,05/06/2003,18/05/2019

代码的这一部分将您的"由于date命令不接受DD/MM/YY的日期输入,因此将您的输入从DD/MM/YYY改为MM/DD/YY。然后,它循环遍历重新排列的日期,并将其转换为DD/MM/YYYY格式,并将它们临时存储在temp中。

cat date_samples.csv | tr "," "n" | awk 'BEGIN{FS=OFS="/"}{print $2,$1,$3}' | 
while read CMD; do
date -d $CMD +%d/%m/%Y >> temp
done;

该线路CCD_ 4将新线路转换回"并且将输出置于CCD_ 5并且删除CCD_。

使用awk:

awk -F, '{ for (i=1;i<=NF;i++) { split($i,map,"/");if (length(map[3])==1) { map[3]="0"map[3] } "date -d ""map[2]"/"map[1]"/"map[3]"" "+%d/%m/%y"" | getline dayte;close("date -d ""map[2]"/"map[1]"/"map[3]"" "+%d/%m/%y"");$i=dayte }OFS="," }1' file

说明:

awk -F, '{ 
for (i=1;i<=NF;i++) { 
split($i,map,"/"); # Loop through each comma separated field and split into the array map using "/" as the field seperator
if (length(map[3])==1) { 
map[3]="0"map[3] # If the year is just one digit, pad out with prefix 0
} 
"date -d ""map[2]"/"map[1]"/"map[3]"" "+%d/%m/%y"" | getline dayte; # Run date command on day month and year and read result into variable dayte
close("date -d ""map[2]"/"map[1]"/"map[3]"" "+%d/%m/%y""); # Close the date execution pipe
$i=dayte # Replace the field for the dayte  variable
}
OFS="," # Set the output field seperator
}1' file

相关内容

最新更新