在bash中搜索变量和相应的值

时间:2013-07-17 14:36:29

标签: bash

我有以下示例文件:

Jul 16 00:01:24  abc postfix/smtp[28719]: 51AEqwqwq06: to=<simon.naish@xyz.com>, relay=none, delay=0.17, delays=0.17/0/0/0, dsn=4.4.1, status=deferred (connect to 127.0.0.1[127.0.0.1]:10026: Connection refused)
Jul 16 00:01:36  abc postfix/smtp[28655]: E444qw002: to=<r-ff001101082d5bf235740884e558eea95@comms.frong.com>, relay=in.emailct.com[63.20.111.76]:25, delay=39, delays=0.06/0/0.92/38, dsn=2.1.5, status=deliverable (250 2.1.5 r-ff001101082d5bf2355ff8740884e558eea95@comms.thrwwsixtyabc.com )
Jul 16 00:01:43  abc postfix/smtp[28815]: F19Dwq003: to=<sullcrom@em1.SulivanCromwell.com>, relay=em1.SullivanCromwell.com[223.222.222.2]:25, delay=162708, delays=162705/0.3/1.6/0.62, dsn=4.2.2, status=deferred (host em1.SullivanCromwell.com[223.222.222.2] said: 452 4.2.2 Mailbox full (in reply to RCPT TO command))

我想显示“delay =”的最高整数值和文件中的相应行。

示例输出:

longest delay was: **162708** on and at **Jul 16 00:01:43** on server **abc**0

Jul 16 00:01:43  postfix/smtp[28815]: F19Dwq003: to=<sullcrom@emm.SullivanAndCromwell.com>, relay=emm.SullivanCromwell.com[205.22.33.33]:25, delay=162708, delays=162705/0.3/1.6/0.62, dsn=4.2.2, status=deferred (host emm.SullivanCromwell.com[223.222.222.2] said: 452 4.2.2 Mailbox full (in reply to RCPT TO command))

提前致谢

1 个答案:

答案 0 :(得分:1)

所有在一起:

$ data=$(grep -nPo '(?<=delay=)\d+' file | sort -rn -t: -k2 | head -1)
$ line=${data%%:*}
$ delay=${data##*:}
$ awk -v line=$line -v delay=$delay 'NR==line {print "longest delay was **", delay, "** on", $1, $2, "at", $3, "at server",$4, "\n\n",$0}' file
longest delay was ** 162708 ** on Jul 16 at 00:01:43 at server abc 

 Jul 16 00:01:43  abc postfix/smtp[28815]: F19Dwq003: to=<sullcrom@em1.SulivanCromwell.com>, relay=em1.SullivanCromwell.com[223.222.222.2]:25, delay=162708, delays=162705/0.3/1.6/0.62, dsn=4.2.2, status=deferred (host em1.SullivanCromwell.com[223.222.222.2] said: 452 4.2.2 Mailbox full (in reply to RCPT TO command))

解释(剧透:它可能很无聊)

您可以先获得以下信息:

$ grep -nPo '(?<=delay=)\d+' file | sort -rn -t: -k2
3:162708
2:39
1:0

让我们分成几部分:

$ grep -nPo '(?<=delay=)\d+' file
1:0
2:39
3:162708

给出行数和delay=的值。由于我们只想要第一行,我们会head -1。然后我们用sort -rn -t: -k2按数字对其进行排序。第一行将是line number:delay

因此,我们有以下内容来获取delayline

$ grep -nPo '(?<=delay=)\d+' file | sort -rn -t: -k2 | head -1
3:162708

$ line=${data%%:*}  # returns value after :
$ delay=${data##*:} # returns value before :

然后是awk

的时候了
awk -v line=$line -v delay=$delay 'NR==line {print "longest delay was **", delay, "** on", $1, $2, "at", $3, "at server",$4}' file
  • awk -v var=$some_var为awk提供了在命令中使用的会话var的值。
  • NR==line {}会在文件行line内执行操作。
  • {print "longest delay was **", delay, "** on", $1, $2, "at", $3, "at server",$4, "\n\n",$0}按照问题中的方式打印数据。 $1$2 ...对应于该行中的字段位置。 $0对应于整行。