简体   繁体   English

使用grep / sed / awk提取与特定字段对应的字符串

[英]use grep/sed/awk to extract string corresponding to certain field

On my Fedora system, I get the following: 在我的Fedora系统上,我得到以下信息:

$  cat /proc/net/arp 
IP address      HW type     Flags       HW address            Mask     Device
130.48.0.1       0x1         0x2         80:4b:c7:10:3e:41     *        wlp1s0

How can I pipe the result of the Device (in this case the answer is wlp1s0) using a screen editor such as sed or grep or awk? 如何使用屏幕编辑器(例如sed或grep或awk)通过管道传输设备的结果(在这种情况下,答案为wlp1s0)?

Thanks! 谢谢!

$ awk '/^[0-9]/{print $6}' /proc/net/arp 
wlp1s0
  • /^[0-9]/ selects lines that start with digit, ip /^[0-9]/选择以ip开头的行

  • print $6 prints the 6th colum being the Device print $6打印第六列作为设备

To get interface name used to get out of a computer, you can use this: 要获取用于退出计算机的接口名称,可以使用以下命令:

ip route get 8.8.8.8 | awk 'NR==1 {print $5}'
eth0

It will always get the correct, even if more than one inf is online. 即使在线有多个inf,它也始终会正确无误。

awk 'NR>1{print $6}' < /proc/net/arp

如果我们在第一行之后(以摆脱标题“ Device”),则打印第六个字段(由空格分隔)。

Assuming your fields are tab-separated, if the Device always appears as the last column: 如果设备始终显示为最后一列,则假定您的字段用制表符分隔:

$ awk -F'\t' 'NR>1{print $NF}' file
wlp1s0

otherwise: 除此以外:

$ awk -F'\t' 'NR==1{for (i=1;i<=NF;i++) f[$i]=i; next} {print $(f["Device"])}' file
wlp1s0

Four methods: 四种方法:

awk 'NR==1{for (i=1;i<=NF;i++) f[$i]=i; next} {print $(f["HW"])}' </proc/net/arp

awk 'NR==2{print $NF}' < /proc/net/arp

sed -nr '/^[0-9]/s#(.*)* (.*)#\2#gp' /proc/net/arp

sed -nr '/^[0-9]/s#(.*)\*[^a-z]*(.*)#\2#gp'  /proc/net/arp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM