我从一个命令输出,我试图解析它做一些事情。
它看起来像这样并保存为文本文件:
Policy name: example-3 (lf-csd) (LINE 29907) Description: CHANGE00001 Destination_addresses (8): 10.0.0.1/32 ( 10.0.0.1-lk-3r53) ( 3125) 10.0.0.8/32 ( 10.0.0.8-test13) ( 3157) 10.0.0.3/32 ( 10.0.0.3-gdgsd-cd) ( 2806) 10.0.0.9/32 ( 10.0.0.9-fd-fdsb) ( 3123) Destination_address_sets (0): Source_addresses: 10.0.0.7/32 ( 10.0.0.7-IR) ( 5989) Applications: tcp3389 Then: permit Policy name: example-4 (lfs-csd) (LINE 29907) Description: CHANGE00002 Destination_addresses (3): 10.0.0.6/32 ( 10.0.0.1-lk-3r53) ( 3125) 10.0.0.2/32 ( 10.0.0.8-test13) ( 3157) 10.0.0.53/32 ( 10.0.0.3-gdgsd-cd) ( 2806) 10.0.0.94/32 ( 10.0.0.9-fd-fdsb) ( 3123) Destination_address_sets (0): Source_addresses: 10.0.0.53/32 ( 10.0.0.52-IR) ( 5989) Applications: tcp53 Then: permit
我只想留下这段文字:
Source_addresses: 10.0.0.7/32 ( 10.0.0.7-IR) ( 5989) Applications: tcp3389 Source_addresses: 10.0.0.53/32 ( 10.0.0.52-IR) ( 5989) Applications: tcp53
这是我写的:
$reg = (?s)Destination_addresses(.*)Destination_address_sets
Get-Content 10.0.0.12.conf |
ForEach-Object {$_ -replace "$reg","" } |
Out-File 10.0.0.12.conf
如果我测试这个:
$re = [regex]'(?s)Destination_addresses(.*)Destination_address_sets'
并使用
$re.match("Destination_addresses Nothing Destination_address_sets :2142")
它与Destination_addresses Nothing Destination_address_sets的值匹配为true,所以我认为正则表达式很接近,但它选择的数据太多或数据都很少。
我也尝试过:
$stuff = Get-Content 10.0.0.12.conf
$trimmeddata = $stuff -replace "(?s)Destination_addresses(.*)Destination_address_sets", ""
我可能错过了一些简单的东西,但任何帮助都会很棒。
答案 0 :(得分:0)
我不知道powershell,但this stackoverflow表明:
(Select-String -InputObject $myString -Pattern 'Source_addresses:(?:.|\n)*?Applications:.*\n' -AllMatches).Matches
可能是您正在寻找的powershell。至于正则表达式,
https://regex101.com/r/hQ3pO4/2
(Source_addresses:(?:.|\n)*?Applications:.*\n)
表明.*
不会捕获换行符,但(?:.|\n)*?
会捕获换行符。
Source_addresses:
- 字面匹配(?:.|\n)*?
.
- 任何字符(不是换行符)|
- 逻辑OR
\n
- 换行符*?
- 尽可能少地重复以满足整个正则表达式。 (直到Applications:
匹配)Applications:
- 字面匹配.*
- 任何字符(不是换行符),贪婪\n
- 换行符