KSH 从文件读取输入并写入同一行上的 CSV

KSH 从文件读取输入并写入同一行上的 CSV

我有以下输出并希望输出如下:

从:

GigabitEthernet0/0 is up, line protocol is up
     1 input errors, 0 CRC, 0 frame, 1 overrun, 0 ignored
     275 output errors, 0 collisions, 3 interface resets
GigabitEthernet0/1 is up, line protocol is up
     0 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored
     42 output errors, 0 collisions, 3 interface resets

收件人:(CSV 格式)

Interface, In Errors, Out Errors
GigabitEthernet0/0, 1, 275
GigabitEthernet0/1, 0, 42

当我将上面的内容放入 for 循环中时,我会得到交错的输出,因为我在每个循环的回合进行 grep 操作

这是我的脚本

for line in $(cat $DATAFILE/$rname.intfs)
do
     intf=$(echo $line | grep "line protocol is " | awk '{print $1}')
     inerrs=$(echo $line | grep "input error" | sed 's/^[ \t]*//;s/[ \t]*$//' | awk '{print $1}')
     outerrs=$(echo $line | grep "output error" | sed 's/^[ \t]*//;s/[ \t]*$//' | awk '{print $1}')
     echo "$intf,$inerrs,$outerrs" >intf.csv
done

任何帮助表示赞赏

谢谢

杰伊

答案1

Awk解决方案(没有外壳循环和管道链):

awk 'BEGIN{ OFS=", "; print "Interface, In Errors, Out Errors" }
     /line protocol /{ ifc=$1 }
     /input errors/{ in_err=$1 }
     /output errors/{ print ifc, in_err, $1 }' "$DATAFILE/$rname.intfs"

输出:

Interface, In Errors, Out Errors
GigabitEthernet0/0, 1, 275
GigabitEthernet0/1, 0, 42

相关内容