最后使用sed和awk进行分析以创建csv文件



因此,我正在尝试创建一个awk脚本来遍历最后一个命令的输出,以便将其转换为csv文件。我遇到的问题是,行匹配了好几次,我不知道如何防止这种情况发生;我决不是一个awk专家(这次演习的部分原因(

sed插入的原因是缺少"sed";列";。

命令按摩最后一个命令并调用awk脚本:

last -w -F | sed -r 's/[[:space:]{23,}/ unknown /;s/(crash|down)/1 unknown /' | awk -f awktest.awk

(附带说明一下,这里的sub是在我决定用sed测试插入列之前(

awktest.awk

BEGIN { print "user,tty/pts,connection_from,login_time,state,logoff_time,total_time"}
{if ($1 ~/reboot/) {print $1","$2","$3","$4","($5" "$6" "$7" "$8" "$9)","$10","($11" "$12" "$13" "$14" "$15","$16)}}
{if ($1 ~/root/ && $2 ~/tty/) { sub($3,"null") ;  print $1","$2","$3","($4" "$5" "$6" "$7" "$8)","$9","($10","$11","$12" "$13" "$14)}}
#{if ( NF > 14) { print $1","$2","$3","($4" "$5" "$6" "$7" "$8 )","$9","($10" "$11" "$12" "$13" "$14)","$15 }}
{if ($3 == "unknown" && $11 !="unknown") { print $1","$2","$3","($4" "$5" "$6" "$7" "$8 )","$9","($10" "$11" "$12" "$13" "$14)","$15 }}
#{if ($3 == "unknown") { print $1","$2","$3","( $4" "$5" "$6" "$7" "$8 )","$9","($10","$11",")$12}}
{if ($11 == "unknown") { print $1","$2","$3","( $4" "$5" "$6" "$7" "$8 )","$9","($10","$11",")$12}}

正如你所看到的,我已经尝试了多种方法,但要么重复,要么缺少行。副本清晰:

root,tty2,null,Sun Jul 19 13:25:38 2020,-,down,unknown,(00:01)
root,tty2,null,Sun Jul 19 13:25:38 2020,-,down,unknown,(00:01)

是的,我知道,不漂亮;但我在试验;我被卡住了,一直在读sed和awk的书,疯狂地在谷歌上搜索,毫无进展;在这一点上,我认为我看得太久了,没有取得任何进展。

我做错了什么?

#编辑以提高清晰度

(删除了一些空白以使其更干净(最后一个命令示例:

root  tty3         Mon Jun  8 09:49:56 2020 - down           (00:00)
foo :0    0        Mon Jun  8 09:49:16 2020 - down                      (00:01)
reboot   system boot  5.6.16-300.fc32.x86_64 Mon Jun  8 09:48:28 2020 - Mon Jun  8 09:50:54 2020  (00:02)
roncioiu :0          Thu Jun 18 10:19:29 2020 - Thu Jun 18 10:20:19 2020  (00:00)

#所需状态列:

  • 时间戳与((中的时间戳一样算作一列
"user,tty/pts,connection_from,login_time,state,logoff_time,total_time"

因此,由于@tink的温和催促,我最终选择了一行代码并放弃了脚本。只需要一点点数据。

谢谢你的小费!换一种方式做,我失去了理智。

last -a -w --time-format iso | sed -r 's/sboots//g;/^$/d;/wtmp/d;/(crash|down)/s/$/ unknown /' | awk 'BEGIN { print "user,pts/tty,login_time,state,logoff_time,total_time,host "} { print $1","$2","$3","$4","$5","$6","$7}'

相关内容

  • 没有找到相关文章

最新更新