我有此日志文本:
1. SNMPv2-SMI::enterprises.37447.2.1.1.1 type=4 value=STRING: "Test warn level"
2. SNMPv2-SMI::enterprises.37447.2.1.1.2 type=4 value=STRING: "WARN"
3. SNMPv2-SMI::enterprises.37447.2.1.1.3 type=4 value=STRING: "PSBA2STOR051"
4. SNMPv2-SMI::enterprises.37447.2.1.1.4 type=4 value=STRING: "AF-201969"
5. SNMPv2-SMI::enterprises.37447.2.1.1.5 type=4 value=STRING: "PSBA2STOR051"
6. SNMPv2-SMI::enterprises.37447.2.1.1.6 type=4 value=STRING: "117813866"
7. SNMPv2-SMI::enterprises.37447.2.1.1.7 type=4 value=STRING: "test"
8. SNMPv2-SMI::enterprises.37447.2.1.1.8 type=4 value=STRING: "test"
请注意,订单号在我的日志中不存在
我只需要提取
Test warn level
test
test
结果必须为:测试警告级别:test-test
我已经尝试过了:
(SNMPv2-SMI::enterprises.37447.2.1.1.1.*)\n.*\n.*\n.*\n.*\n.*\n(.*SNMPv2-SMI::enterprises.37447.2.1.1.7.*)\n(.*SNMPv2-SMI::enterprises.37447.2.1.1.8.*)
但是它不能像我需要的那样返回孔线
答案 0 :(得分:1)
您可以这样做:
sed -e 's/.*37447.2.1.1.[178].*"\(.*\)"/\1/;t;d' test.log
正则表达式搜索包含37447.2.1.1.1,.7或.8的行:37447.2.1.1.[178]
在这些行中,仅使用引号之间的内容:"\(.*\)"
不匹配的行(t
)被抑制(d
):t;d
答案 1 :(得分:0)
使用:
/"(Test warn level|test)"+\s*$/gm
您可以检测到
"Test warn level"
"test"
"test"
和$1
,您可以省略双引号和空格。
答案 2 :(得分:0)
此表达式可能会提取我们想要的值,
.*?37447\.2\.1\.1\.[817].*?value=string\s*:\s*"([^"]+)"
使用此捕获组([^"]+)
。
在this demo的右上角对表达式进行了说明,如果您想探索/简化/修改它,在this link中,您可以观察它如何与某些示例输入步骤匹配一步一步,如果您喜欢。
答案 3 :(得分:0)
因为在匹配起始文本后使用.*
,所以您获得了整行的匹配。
在您的示例中,您似乎想使用SNMPv2-SMI::enterprises.37447.2.1.1.1
的开头来获取3个捕获组,并指定最后一个数字,可以是1、7或8。
这看起来像是一个大图案(可以缩短),但是您可以使用否定的超前行为来检查该行是否不包含要匹配的值。
如果不是,则匹配整行。否则,捕获组中双引号之间的值。
SNMPv2-SMI::enterprises\.37447\.2\.1\.1\.1 [^"]+"([^"]+)"(?:\n(?!SNMPv2-SMI::enterprises\.37447\.2\.1\.1\.7).*)*\nSNMPv2-SMI::enterprises\.37447\.2\.1\.1\.7[^"]+"([^"]+)"\nSNMPv2-SMI::enterprises\.37447\.2\.1\.1\.8 [^"]+"([^"]+)"
要使用Javascript获得结果,可以使用这三个捕获组:
const regex = /SNMPv2-SMI::enterprises\.37447\.2\.1\.1\.1 [^"]+"([^"]+)"(?:\n(?!SNMPv2-SMI::enterprises\.37447\.2\.1\.1\.7).*)*\nSNMPv2-SMI::enterprises\.37447\.2\.1\.1\.7[^"]+"([^"]+)"\nSNMPv2-SMI::enterprises\.37447\.2\.1\.1\.8 [^"]+"([^"]+)"/;
const str = `SNMPv2-SMI::enterprises.37447.2.1.1.1 type=4 value=STRING: "Test warn level"
SNMPv2-SMI::enterprises.37447.2.1.1.2 type=4 value=STRING: "WARN"
SNMPv2-SMI::enterprises.37447.2.1.1.3 type=4 value=STRING: "PSBA2STOR051"
SNMPv2-SMI::enterprises.37447.2.1.1.4 type=4 value=STRING: "AF-201969"
SNMPv2-SMI::enterprises.37447.2.1.1.5 type=4 value=STRING: "PSBA2STOR051"
SNMPv2-SMI::enterprises.37447.2.1.1.6 type=4 value=STRING: "117813866"
SNMPv2-SMI::enterprises.37447.2.1.1.7 type=4 value=STRING: "test"
SNMPv2-SMI::enterprises.37447.2.1.1.8 type=4 value=STRING: "test"`;
let res = str.match(regex);
console.log(`${res[1]}:${res[2]}-${res[3]}`)