convert dateformat in awk, line contains 2 dates a

2019-05-10 16:32发布

i have the following line:

192.168.1.200§Feb 24 10:22:14 2014 GMT§Aug 24 10:22:14 2014 GMT

and I want to convert it into this line with awk (or something else):

2014-02-24 2014-02-24 192.168.1.200

I was able to convert ONE Date with awk, using this command:

awk 'BEGIN { FS="§"} {cmd1="date \"+%Y-%m-%d\" -d \""$2"\""; cmd1 | getline var;  print var}'

but I don't know how to convert the row in one command?

标签: bash shell awk
2条回答
孤傲高冷的网名
2楼-- · 2019-05-10 17:30

Here is one way with awk:

awk -v FS="§" '
BEGIN {
    split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec", month, / /)
    for (i=1; i<=12; i++) { mm[month[i]] = sprintf("%02d",i) }
}
{
    split($2, d1, /[ :]/);
    split($3, d2, /[ :]/); 
    print d1[6]"-"mm[d1[1]]"-"d1[2], d2[6]"-"mm[d2[1]]"-"d2[2], $1
}' file
2014-02-24 2014-08-24 192.168.1.200
  • You create your lookup table in BEGIN statement for all months.
  • Split the 2nd and 3rd field on space and : in to an array.
  • Format and print as desired.
查看更多
淡お忘
3楼-- · 2019-05-10 17:34

Try this:

BEGIN {
    FS="§"
}

{
    cmd1="date \"+%Y-%m-%d\" -d \""$2"\""
    cmd1 | getline var1
    cmd2="date \"+%Y-%m-%d\" -d \""$3"\""
    cmd2 | getline var2
    print var1, var2, $1
}

Usage:

$ cat in.txt
192.168.1.200§Feb 24 10:22:14 2014 GMT§Aug 24 10:22:14 2014 GMT
$  awk -f conv.awk < in.txt
2014-02-24 2014-08-24 192.168.1.200
查看更多
登录 后发表回答