regexp error when filtering command output

家住魔仙堡 提交于 2019-12-11 17:48:39

问题


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


来源:https://stackoverflow.com/questions/23370085/regexp-error-when-filtering-command-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!