输入:
01-DEC-18|"0308"|"RUB"
01-DEC-18|"0308"|"RUB"
01-DEC-18|"0308"|"RUB"
01-DEC-18|"0308"|"RUB"
预期输出:
01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
如何将缩写的月份名称转换为月份编号并实现预期的输出?
答案 0 :(得分:2)
您的意思是这样的吗?
#!/bin/bash
while read -r line; do
# use date to convert first column of line
newdate=$(date -d "${line%%|*}" +"%d-%m-%y")
# print new date and the last two columns
printf "%s|%s\n" "$newdate" "${line#*|}"
done < input
答案 1 :(得分:1)
使用GNU awk(通过抛弃strftile()
和相关(即第3-5行)并定义m["JAN"]="01";m["FEB"]="02";
等可以轻松地转换为其他awk):
$ awk 'BEGIN { # prime a hash for month abbr.
FS=OFS="-" # split at -
Ms=28*24*60*60 # "month seconds"
for(t=1;t<=12;t++) # iterate all month numbers
m[toupper(strftime("%b",t*Ms))]=sprintf("%02d",t) # hash m["JAN"]="01"
}
{
$2=m[$2] # retrieve month # from hash
}1' file # output
输出数据:
01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
01-12-18|"0308"|"RUB"
对于100万条数据记录,此脚本运行1.7秒:
real 0m1.719s
user 0m1.688s
sys 0m0.032s
答案 2 :(得分:1)
带有数组的蛮力方法:
awk '
BEGIN {
FS = OFS = "-"
split("", m)
n = split("JAN-FEB-MAR-APR-MAY-JUN-JUL-AUG-SEP-OCT-NOV-DEC", s)
for (i=1; i<=n; i++)
m[s[i]] = sprintf("%0.2i", i)
}
{ $2 = m[$2]; print }
' file
真的是蛮力的(&死得很简单):
awk '
BEGIN {
FS = OFS = "-"
split("", m)
m["JAN"] = "01"
m["FEB"] = "02"
m["MAR"] = "02"
m["APR"] = "03"
m["MAY"] = "05"
m["JUN"] = "06"
m["JUL"] = "07"
m["AUG"] = "08"
m["SEP"] = "09"
m["OCT"] = "10"
m["NOV"] = "11"
m["DEC"] = "12"
}
{ $2 = m[$2]; print }
' file
或使用索引:
awk -F- -v OFS=- '{
m = index(" JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC", $2) / 3
$2 = sprintf("%0.2i", m)
print
}' file