有没有办法只使用grep
,awk
来回复第二或第三,第四段......?
如何获取lo
段,我知道可以使用命令ifconfig lo
,但如果使用其他命令。 ifconfig
的输出是:
eth0 Link encap:Ethernet HWaddr 00:25:22:b2:8b:0d
inet addr:192.168.1.22 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::225:22ff:feb2:8b0d/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:100979 errors:0 dropped:0 overruns:0 frame:0
TX packets:70753 errors:0 dropped:0 overruns:0 carrier:1
collisions:0 txqueuelen:1000
RX bytes:129240044 (129.2 MB) TX bytes:7355272 (7.3 MB)
Interrupt:29
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
答案 0 :(得分:3)
您可以使用awk
轻松过滤段落编号或界面名称。
对于段落编号,只需指定awk 'NR==1' RS=''
的记录:
# First record
$ ifconfig | awk 'NR==1' RS=''
eth0 Link encap:Ethernet HWaddr 00:25:22:b2:8b:0d
inet addr:192.168.1.22 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::225:22ff:feb2:8b0d/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:100979 errors:0 dropped:0 overruns:0 frame:0
TX packets:70753 errors:0 dropped:0 overruns:0 carrier:1
collisions:0 txqueuelen:1000
RX bytes:129240044 (129.2 MB) TX bytes:7355272 (7.3 MB)
Interrupt:29
# Second Record
$ ifconfig | awk 'NR==2' RS=''
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
如果您想按接口名称而不是记录号码进行过滤,请awk '$1=="eth0"' RS=''
:
# Interface lo
$ ifconfig | awk '$1=="lo"' RS=''
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
# Interface eth0
$ ifconfig | awk '$1=="eth0"' RS=''
eth0 Link encap:Ethernet HWaddr 00:25:22:b2:8b:0d
inet addr:192.168.1.22 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::225:22ff:feb2:8b0d/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:100979 errors:0 dropped:0 overruns:0 frame:0
TX packets:70753 errors:0 dropped:0 overruns:0 carrier:1
collisions:0 txqueuelen:1000
RX bytes:129240044 (129.2 MB) TX bytes:7355272 (7.3 MB)
Interrupt:29
但我不知道ifconfig eth0
或ifconfig lo
会出现什么问题。
答案 1 :(得分:0)
使用awk:
BEGIN {
RS = ""
}
NR == 3 {
print
exit
}
打印第三段。将“3”更改为您喜欢的任何内容。请注意,将记录分隔符设置为空字符串会使awk像往常一样处理段落而不是行。
您可以像这样运行:
awk -f above.awk input.txt
答案 2 :(得分:0)
使用pattern range,这是使用sed
的一种方式。它还将删除最后一个空行:
ifconfig | sed -n '/^lo/,/^$/ { /^$/!p }'
awk
解决方案:
ifconfig | awk '$1=="lo"' RS=