使用 sed 消除中间行

使用 sed 消除中间行

我有以下日志格式

2017-12-22T23:32:07-05:00 ServerABC sshd[22549]: Accepted password for JohnBlezard from 192.168.1.1 port 81111 ssh2
2017-12-22T23:32:07-05:00 ServerABC sshd[60944]: Accepted password for JohnBlezard from 192.168.1.1 port 81111 ssh2
2017-12-22T23:32:07-05:00 ServerABC sshd[1787]: [ID 800047 dns.info] Accepted password for JohnBlezard from 192.168.1.1 port 81111 ssh2
2017-12-22T23:32:13-05:00 ServerABC sshd[1367]: [ID 800047 dns.info] Accepted password for JohnBlezard from 192.168.1.1 port 81111 ssh2
2017-12-22T23:32:14-05:00 ServerABC sshd[36061]: Accepted password for JohnBlezard from 192.168.1.1 port 81111 ssh2
2017-12-22T23:32:17+00:00 ServerABC sshd[31616]: Accepted password for JohnBlezard from 192.168.1.1 port 81111 ssh2

我一直在使用下面的命令来解析它。但是我似乎无法摆脱“[ID:800047 dns.info]”

有没有更简单的方法使用 sed 消除中间行?

grep -E '(Accepted|for JohnBlezard)' testing.txt | grep "JohnBlezard from" | awk '{print $2, $5, $7, $9, $11}'

预期结果应该如下

[ServerABC] [password] [JohnBlezard] [IP Address] 

但解析后,我注意到在某些行中它的结果是

[ServerABC] [ID 800047] [Accepted] [for] [from]

答案1

与单awk命令:

awk '/Accepted .+ for JohnBlezard/{ 
         if ($4 == "[ID") { $5 = $8; $7 = $10; $9 = $12; $11 = $14 }
         print $2, $5, $7, $9, $11
     }' test.txt

输出:

ServerABC password JohnBlezard 192.168.1.1 81111
ServerABC password JohnBlezard 192.168.1.1 81111
ServerABC password JohnBlezard 192.168.1.1 81111
ServerABC password JohnBlezard 192.168.1.1 81111
ServerABC password JohnBlezard 192.168.1.1 81111
ServerABC password JohnBlezard 192.168.1.1 81111

答案2

您可以使用以下命令删除这些行grep -v

man grep

       -v, --invert-match
          Invert the sense of matching, to select non-matching lines.  (-v is specified by POSIX.)

所以

$ cat test
2017-12-22T23:32:07-05:00 ServerABC sshd[22549]: Accepted password for JohnBlezard from 192.168.1.1 port 81111 ssh2
2017-12-22T23:32:07-05:00 ServerABC sshd[60944]: Accepted password for JohnBlezard from 192.168.1.1 port 81111 ssh2
2017-12-22T23:32:07-05:00 ServerABC sshd[1787]: [ID 800047 dns.info] Accepted password for JohnBlezard from 192.168.1.1 port 81111 ssh2
2017-12-22T23:32:13-05:00 ServerABC sshd[1367]: [ID 800047 dns.info] Accepted password for JohnBlezard from 192.168.1.1 port 81111 ssh2
2017-12-22T23:32:14-05:00 ServerABC sshd[36061]: Accepted password for JohnBlezard from 192.168.1.1 port 81111 ssh2
2017-12-22T23:32:17+00:00 ServerABC sshd[31616]: Accepted password for JohnBlezard from 192.168.1.1 port 81111 ssh2

预期结果

$ grep -E '(Accepted|for JohnBlezard)' test | grep -v "\[ID" | grep "JohnBlezard from" | awk '{print $2, $5, $7, $9, $11}'
ServerABC password JohnBlezard 192.168.1.1 81111
ServerABC password JohnBlezard 192.168.1.1 81111
ServerABC password JohnBlezard 192.168.1.1 81111
ServerABC password JohnBlezard 192.168.1.1 81111

答案3

你可以尝试使用这个 sed

sed -E '
 h
  s/(.*: (\[[^\]*\] )*)//
  s/(( *[^ ]*){6})(.*)/\1/
  s/( *[^ ]* )([^ ]*)/[\2] /g
 x
  s/([^ ]* )([^ ]*).*/ [\2]/
 G
  y/\n/ /
' infile

相关内容