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:
$ 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. 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.
You can combine all three of them (including the cat
which is needless here):
dest=03043836; mask=FFFFFFFF; va=1;
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:
---------
$ 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?
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.