如何修复在 Linux shell 脚本中使用 grep 命令编写的 IP 过滤器正则表达式?

问题描述 投票:0回答:2

它在 shell 脚本中不起作用,但在 javascript 中,它工作正常,有什么问题吗?

我只想过滤掉所有不在2~254范围内的IP,例如忽略

255

shell脚本

只想过滤掉

192.168.18.255

  1. 当前有用的输入IP:

    192.168.18.195 192.168.18.255

  2. 想要输出IP:

    192.168.18.195

#!/usr/bin/env bash

IPs=$(ifconfig | grep -oE '(192\.168\.1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])')
echo $IPs
# 192.168.18.195 192.168.18.255 ❌

IPs1=$(ifconfig | grep -oE '192\.168\.(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.([2-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])')
echo $IPs1
# 192.168.18.195 192.168.18.25 ❌

IPs2=$(ifconfig | grep -oE '192\.168\.(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.([2-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])$')
echo $IPs2
# ❌

# wanted, ignore 192.168.18.255 ❓
# IPs=$(ifconfig | grep -oE '❓')
# echo $IPs
# 192.168.18.195

$ ifconfig
# The output is too long, ignore it here, Please see the link below

ifconfig
输出链接:https://gist.github.com/xgqfrms/a9e98b17835ddbffab07dde84bd3caa5

javascript

这只是用于测试忽略IP

255
效果很好。


function test(n) {
  let reg = /192\.168\.(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.([2-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])$/;
   for (let i = 0; i < n; i++) {
     let result = reg.test(`192.168.18.${i}`);
     if(result) {
       // console.log(`192.168.18.${i} ✅`, i, result)
     } else {
       console.log(`192.168.18.${i} ❌`, i, result)
     }
   }
}

test(256);

192.168.18.0 ❌ 0 false
192.168.18.1 ❌ 1 false
192.168.18.255 ❌ 255 false

      

参考

https://regexper.com/

https://regex101.com/

regex shell filter grep ip
2个回答
1
投票

由于您的

ifconfig
输出不仅包含IP,还包含围绕它的文本,因此
$
不是IP结束的唯一有效标记。

最简单的方法是将其替换为

\b
:单词边界。但只有当您使用 GNU
grep
.

时它才会起作用

如果您的 grep 不支持

\b
,您可以使用
([[:space:]]|$)
[^0-9]
代替。如果它是(空格或行尾)或相应的非数字,它将捕获 IP 后面的符号。

您的

ifconfig
输出存储在文件
input_file.txt
中的命令示例:

$ ifconfig > input_file.txt

$ cat input_file.txt | grep -oE '192\.168\.(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.([2-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])([[:space:]]|$)'
192.168.18.195 

演示在regex101.


0
投票

解决方案

测试环境 结果
macOS 13.1
树莓派操作系统 x64
  1. \b
#!/usr/bin/env bash

IPs=$(ifconfig | grep -oE '192\.168\.(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.([2-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])\b')
echo $IPs
# 192.168.18.195

  1. [[:space:]]
#!/usr/bin/env bash

IPs=$(ifconfig | grep -oE '192\.168\.(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.([2-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4])[[:space:]]')
echo $IPs
# 192.168.18.195

© www.soinside.com 2019 - 2024. All rights reserved.