bash 获取grep匹配后的下一个单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18708849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:30:54  来源:igfitidea点击:

get the next word after grep matching

bashawkgrep

提问by progloverfan

I'm using this command to retrieve the signal average power of a client connected to an Access Point:

我正在使用此命令来检索连接到接入点的客户端的信号平均功率:

iw dev wlan0 station dump | grep -E 'Station|signal avg': 

I got the following info:

我得到以下信息:

Station"my_MAC_Address" (on wlan0)

“my_MAC_Address”(在 wlan0 上)

signal avg:-46 dBm

信号平均值:-46 dBm

In bold is what I matches with grep and I just only want to get the word after that matching, i.e the MAC address and the number -46. I've been playing with awk but without success. hope you can help me!

粗体是我与 grep 匹配的内容,我只想得到匹配后的单词,即 MAC 地址和数字 -46。我一直在玩 awk 但没有成功。希望你能帮我!

回答by Aleks-Daniel Jakimenko-A.

iw dev wlan0 station dump | grep -Po '(?<=Station\s|signal avg:\s)[^\s]*'

This regexp uses a so-called lookbehindsyntax. You can read about it here

此正则表达式使用所谓的lookbehind语法。你可以在这里阅读

Example output:

示例输出:

00:11:22:33:44:55
-40

Update:

更新:

Thanks for voting this answer up. Now I know another solution:

感谢您对这个答案投票。现在我知道另一个解决方案:

iw dev wlan0 station dump | grep -Po '(Station\s|signal avg:\s)\K[^\s]*'

Which is actually a shorthand for the solution above. \Kbasically means "forget everything before its occurance".

这实际上是上述解决方案的简写。\K基本上意味着“在它发生之前忘记一切”。

回答by Charles Chow

You can use two grep to do this as well

您也可以使用两个 grep 来执行此操作

iw dev wlan0 station dump | grep -E 'Station|signal avg' | grep -o [^'Station|signalavg'].*

回答by William Pursell

One possible awk solution which plays fast and loose with whitespace is:

一种可能的 awk 解决方案是:

... | awk ' == "Station" { print  } 
             == "signalavg:" { print  }'