我有一系列 CSV 文件,其第二个字段是日期:
R.OUSE BOURTON MILL,2000-03-22T14:50:00,Ammoniacal Nitrogen as N,0.03,mg/l
如何将所有文件的日期格式更改为 DD/MM/YYYY?不需要测量时间。
太感谢了
答案1
和磨坊主,使用其内置strptime
函数strftime
:
$ mlr --fs ',' --ocsvlite --headerless-csv-output put '
$2 = strftime(strptime($2,"%Y-%m-%dT%H:%M:%S"),"%d/%m/%Y")
' file.csv
R.OUSE BOURTON MILL,22/03/2000,Ammoniacal Nitrogen as N,0.03,mg/l
答案2
为什么要攻击?
从命令行:
sed -E 's,([0-9]{4})-([0-9]{2})-([0-9]{2}),\3/\2/\1,g' test
结果:
R.OUSE BOURTON MILL,22/03/2000T14:50:00,Ammoniacal Nitrogen as N,0.03,mg/l
答案3
匹配并重新排列时间部分awkgensub。
$ awk 'BEGIN {FS=OFS=","} {$2=gensub(/(.+)-(.+)-(.+)T.*/,"\\3/\\2/\\1","g",$2)} 1' file.csv # >> output.csv
(nawk 版本):
$ awk 'BEGIN {FS=OFS=","} {split(substr($2,0,10),a,"-"); $2=sprintf("%s/%s/%s",a[3],a[2],a[1])} 1' file.csv # >> output.csv
如果只想转换时间格式,那么时代或许是更好的选择。
#!/usr/bin/awk -f
#
# example.awk
#
BEGIN {
FS=OFS=","
} {
split(substr($2,0,10),a,"-")
$2=mktime(sprintf("%s %s %s %s %s %s",a[1],a[2],a[3],00,00,00))
} 1
$ awk -f example.awk file.csv # >> output.csv
答案4
bash
这是一个使用和的合理解决方案date
:
#!/bin/bash
IFS=,
while read -r line; do
fields=($line) # Split string into fields
fields[1]=$(date --date="${fields[1]}" +%d/%m/%Y) # Transform the second date
echo "${fields[*]}" # Reassemble fields
done <file.csv >>output.csv