regexp error when filtering command output

2019-08-28 23:08发布

问题:

I want to filter the lines from the following command:

$ cat /proc/net/route
Iface   Destination     Gateway         Flags   RefCnt  Use     Metric  Mask            MTU     Window  IRTT                               
br-lan  01020300        C0A80101        0003    0       0       3       FFFFFF00        0       0       0                                  
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 want to extract only the line containing the Destination 01020300 and the Mask FFFFFF00

I tried with the following regexp but it does not works

cat /proc/net/route | grep "[^ \t\v]\+[ \t\v]\+$dest[ \t\v]\+[^ \t\v]\+[ \t\v]\+[^ \t\v]\+[ \t\v]\+[^ \t\v]\+[ \t\v]\+[^ \t\v]\+[ \t\v]\+[^ \t\v]\+[ \t\v]\+$mask"

I newbe wuth the regexp format. could you help me with a good regexp for this case?

回答1:

Maybe it is easier to work with awk for this:

$ awk '$2=="01020300" && $8=="FFFFFF00"' file
br-lan  01020300        C0A80101        0003    0       0       3       FFFFFF00        0       0       0     

This way you can refer to the 2nd and 8th columns and check its value, without having to worry about the format.

In case your file separates fiels with tabs instead of spaces, use:

awk -F"\t" '$2=="01020300" && $8=="FFFFFF00"' file

And in case you want to give this values from bash variables, you can do (see comments, as Glenn Jackman, Etan Reisner and Ed Morton gave nice explanations):

awk -v d="$dest" -v m="$mask" '$2==d && $8==m' file