简体   繁体   中英

use grep/sed/awk to extract string corresponding to certain field

On my Fedora system, I get the following:

$  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?

Thanks!

$ awk '/^[0-9]/{print $6}' /proc/net/arp 
wlp1s0
  • /^[0-9]/ selects lines that start with digit, ip

  • print $6 prints the 6th colum being the Device

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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