grep在变量中按模式的精确字符串

时间:2016-06-23 11:27:55

标签: bash awk sed grep match

我想在变量

中按模式grep精确字符串
ip="192.168.100.1"
arp -a | grep "$ip"

输出如下内容:

# arp -a | grep "$ip"
? (192.168.10.1) at 66:ca:6d:88:57:cd [ether]  on br0
? (192.168.10.15) at 3c:15:a0:05:b5:94 [ether]  on br0

但我想要其他PC没有IP IP 另外我只有嵌入式grep(minimalistic)我也有awk,sed。

我正在尝试这个但没有成功:

arp -a | grep "\b$ip\b"

2 个答案:

答案 0 :(得分:1)

\b等词边界不适用于标准grep。从您发布的输出片段看起来这对您有用:

$ ip="192.168.10.1"
$ grep -F "($ip)" file
? (192.168.10.1) at 66:ca:6d:88:57:cd [ether]  on br0

即。只需使用-F作为字符串而不是正则表达式比较,并明确包含输入中IP地址周围出现的分隔符。

FWIW,请问:

$ awk -v ip="($ip)" 'index($0,ip)' file
? (192.168.10.1) at 66:ca:6d:88:57:cd [ether]  on br0

并且您无法在sed中以合理的方式执行此操作,因为sed仅支持正则表达式比较,而不支持字符串(请参阅Is it possible to escape regex metacharacters reliably with sed)。

答案 1 :(得分:0)

如果我正确理解您所说的内容,您只想在命令中添加-o选项,-o选项仅打印匹配行的匹配(非空)部分,每个这样的部分都在一个单独的输出线上。

arp -a | grep -o "$ip"
相关问题