简体   繁体   English

如何仅用1个命令收集2个awk命令

[英]How to gather 2 awk commands in only 1 command

I have the following output 我有以下输出

$ cat /proc/net/route
Iface   Destination     Gateway         Flags   RefCnt  Use     Metric  Mask            MTU     Window  IRTT                               
br-lan  03043836        C0A80101        0007    0       0       5       FFFFFFFF        0       0       0                                  
br-lan  C0A80100        00000000        0001    0       0       0       FFFFFF00        0       0       0  

I use the awk to extract the line containing the Destination 03043836 and the Mask FFFFFFFF and then I use the awk another time to display the first elment from the extracted line: 我使用awk提取包含目标03043836和Mask FFFFFFFF ,然后再次使用awk从提取的行中显示第一个元素:

$ dest=03043836; mask=FFFFFFFF; va=1;
$ cat /proc/net/route | awk '$2=="'"$dest"'" && $8=="'"$mask"'"' | awk '{print $'"$va"'}'
br-lan

Now I want to gather both awk commands in only one awk command. 现在,我只想在一个awk命令中收集两个awk命令。 How to do that? 怎么做?

dest=03043836; mask=FFFFFFFF; va=1;
awk -v dest="$dest" -v mask="$mask" -v va="$va" '$2==dest && $8==mask {print $va}' /proc/net/route

-v is used to assign a value to a variable. -v用于为变量分配值。

You can combine all three of them (including the cat which is needless here): 您可以将它们全部三者结合起来(包括这里不需要cat ):

dest=03043836; dest = 03043836; mask=FFFFFFFF; mask = FFFFFFFF; va=1; va = 1;

awk -v dest="${dest}" -v mask="${mask}" -v va="${va}" {print $va}' /proc/net/route awk -v dest =“ $ {dest}” -v mask =“ $ {mask}” -v va =“ $ {va}” {print $ va}'/ proc / net / route

This is not an answer, just a couple of small examples demonstrating why you should use Ashkan's answer: 这不是答案,只是几个小例子,说明了为什么应该使用Ashkan的答案:

---------
$ x="hello world"

$ awk -v y="$x" 'BEGIN{print y}'
hello world

$ awk 'BEGIN{print "'"$x"'"}'
hello world

---------
$ x="hello
world"

$ awk -v y="$x" 'BEGIN{print y}'
hello
world

$ awk 'BEGIN{print "'"$x"'"}'
awk: cmd. line:1: BEGIN{print "hello
awk: cmd. line:1:             ^ unterminated string
awk: cmd. line:1: BEGIN{print "hello
awk: cmd. line:1:             ^ syntax error

---------
$ x="hello world\\"

$ awk -v y="$x" 'BEGIN{print y}'
hello world\

$ awk 'BEGIN{print "'"$x"'"}'
awk: cmd. line:1: BEGIN{print "hello world\"}
awk: cmd. line:1:             ^ unterminated string
awk: cmd. line:1: BEGIN{print "hello world\"}
awk: cmd. line:1:             ^ syntax error

How would you prefer your script to behave in the latter 2 cases? 在后两种情况下,您希望脚本如何表现?

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

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