4

我正在尝试从日志输出创建 CSV 文件

示例两行日志文件:

May 24 2013 18:13:24 ROUTER1 %%01IFNET/4/UPDOWN(l): The state of interface GigabitEthernet0/0/22 was changed to DOWN.
May 24 2013 17:59:33 ROUTER1 %%01FIB/3/REFRESH_END(l): FIB refreshing end, the refresh group map is 0!

预期输出:

May 24 2013 18:13:24,ROUTER1,01IFNET,4,UPDOWN,The state of interface GigabitEthernet0/0/22 was changed to DOWN.
May 24 2013 17:59:33,ROUTER1,01IFNET,3,REFRESH_END,FIB refreshing end, the refresh group map is 0!

我可以设法用这个 awk 命令得到一些正确的部分:

cat test.log | awk -F'[" "%%/(l)]' '{print $1" "$2" "$3","$4","$5","$8","$9","$10","}'

输出:

May 24 2013 18:13:24,ROUTER1,01IFNET,4,UPDOWN,
May 24 2013 17:59:33,ROUTER1,01IFNET,3,REFRESH_END,

但是如何捕获“(l):”之后的多列描述文本,例如“ FIB刷新结束,刷新组映射为0! ”或“接口GigabitEthernet0/0/22的状态已更改为DOWN。 ”。请指教。

4

3 回答 3

2

awk 可以处理多个分隔符:

$ awk -F'[(/% ]' '{printf "%s",$1" "$2" "$3" "$4" "$5","$8","$9","$10",";for(i=12;i<=NF;i++)printf "%s ",$i;print ""}' file
May 24 2013 18:13:24 ROUTER1,01IFNET,4,UPDOWN,The state of interface GigabitEthernet0 0 22 was changed to DOWN.
May 24 2013 17:59:33 ROUTER1,01FIB,3,REFRESH_END,FIB refreshing end, the refresh group map is 0!
于 2013-05-28T12:40:34.707 回答
1

由于这是单行的简单替换,我只使用 sed,例如:

$ cat file
May 24 2013 18:13:24 ROUTER1 %%01IFNET/4/UPDOWN(l): The state of interface GigabitEthernet0/0/22 was changed to DOWN.
May 24 2013 17:59:33 ROUTER1 %%01FIB/3/REFRESH_END(l): FIB refreshing end, the refresh group map is 0!

$ sed -r 's/(([^ ]+ +){3}[^ ]+) +([^ ]+)[ %]+([^/]+)\/([^/]+)\/([^(]+)[^ ]+ +(.*)/\1,\3,\4,\5,\6,\7/' file
May 24 2013 18:13:24,ROUTER1,01IFNET,4,UPDOWN,The state of interface GigabitEthernet0/0/22 was changed to DOWN.
May 24 2013 17:59:33,ROUTER1,01FIB,3,REFRESH_END,FIB refreshing end, the refresh group map is 0!

但如果您愿意,这里有一个 awk 解决方案:

$ awk -F' %%|[(][^)+][)]: ' -v OFS="," '{$1=substr($1,1,20) OFS substr($1,22); gsub(/\//,OFS,$2)}1' file
May 24 2013 18:13:24,ROUTER1,01IFNET,4,UPDOWN,The state of interface GigabitEthernet0/0/22 was changed to DOWN.
May 24 2013 17:59:33,ROUTER1,01FIB,3,REFRESH_END,FIB refreshing end, the refresh group map is 0!

并不是说这不会从您的第一行输入中删除“ Gigabit ...”文本,因为您没有说明如何识别它 - 您是要在“interface”之后删除文本还是以“Gigabit”开头或在一些空格或其他东西之后?

于 2013-05-28T12:45:17.930 回答
0

我希望在“界面”之后删除的东西不是错字......

又脏又快:(虽然应该有更好的方法..)

awk -F'\\(l\\): ' -v OFS="," '{gsub(" %%|/"," ",$1);gsub(/ /,",",$1);for(i=1;i<=3;i++)sub(/,/," ",$1)}$2~/of interface /{gsub(/interface.*/,"interface",$2)}1' file

May 24 2013 18:13:24,ROUTER1,01IFNET,4,UPDOWN,The state of interface
May 24 2013 17:59:33,ROUTER1,01FIB,3,REFRESH_END,FIB refreshing end, the refresh group map is 0!
于 2013-05-28T12:48:26.120 回答