使用 Powershell 子字符串和正则表达式提取可变数量的标记
use Powershell substring and Regex to extract a variable number of tokens
我从这个论坛获得了使用下面的 Powershell 和 Regex 的帮助
if((get-content -Raw c:\config.txt) -match '(?ms)^999.*?(?=\r?\n\S|\Z)')
{ $matches[0]}
从下面的配置中成功提取未使用的 vlan 999 的正确信息
1 default active Fa0/4, Fa0/5, Fa0/6, Fa0/7, Fa0/8
120 Camera active Fa0/2
130 Student active Fa0/1
100 Management active
999 Unused active Fa0/10, Fa0/11, Fa0/12, Fa0/13,
Fa0/14, Fa0/15, Fa0/16, Fa0/17
Fa0/18, Fa0/19
然后我可以使用下面的子字符串方法提取端口号作为
Fa0/10, Fa0/11, Fa0/12, Fa0/13, Fa0/14, Fa0/15, Fa0/16, Fa0/17 Fa0/18, Fa0/19
$Unused_VLAN = $Matches[0]
$Unused_ports = Unused_VLAN.substring (48, 77)
我的问题是我必须在多个配置文件中提取此信息,并且每个配置文件都有不同数量的未使用端口。
我的问题是有比使用子字符串方法提取未使用端口更好的方法,因为我必须指定字符串的确切起始位置和结束位置以提取端口,因此其他配置文件具有不同数量的未使用的端口然后我使用的子字符串不起作用。
使用 PowerShell 的 -split
运算符的一元形式的实用解决方案:
# Get the block of relevant lines as a single string.
$unusedVlan = if ((Get-Content -raw c:\config.txt) -match '(?ms)^999.*?(?=\r?\n\S|\Z)')
{ $Matches[0]}
# Split the string into an array of token by whitespace,
# remove all "," instances,
# and skip the first 3 tokens
# (the tokens *before* the port numbers, namely '999', 'Unused', 'active')
# The result is an *array* of all port numbers: @( 'Fa0/10', 'Fa0/11', ... )
$unusedPorts = (-split $unusedVlan) -replace ',' | Select-Object -Skip 3
# Output the array
$unusedPorts
我从这个论坛获得了使用下面的 Powershell 和 Regex 的帮助
if((get-content -Raw c:\config.txt) -match '(?ms)^999.*?(?=\r?\n\S|\Z)')
{ $matches[0]}
从下面的配置中成功提取未使用的 vlan 999 的正确信息
1 default active Fa0/4, Fa0/5, Fa0/6, Fa0/7, Fa0/8
120 Camera active Fa0/2
130 Student active Fa0/1
100 Management active
999 Unused active Fa0/10, Fa0/11, Fa0/12, Fa0/13,
Fa0/14, Fa0/15, Fa0/16, Fa0/17
Fa0/18, Fa0/19
然后我可以使用下面的子字符串方法提取端口号作为
Fa0/10, Fa0/11, Fa0/12, Fa0/13, Fa0/14, Fa0/15, Fa0/16, Fa0/17 Fa0/18, Fa0/19
$Unused_VLAN = $Matches[0]
$Unused_ports = Unused_VLAN.substring (48, 77)
我的问题是我必须在多个配置文件中提取此信息,并且每个配置文件都有不同数量的未使用端口。
我的问题是有比使用子字符串方法提取未使用端口更好的方法,因为我必须指定字符串的确切起始位置和结束位置以提取端口,因此其他配置文件具有不同数量的未使用的端口然后我使用的子字符串不起作用。
使用 PowerShell 的 -split
运算符的一元形式的实用解决方案:
# Get the block of relevant lines as a single string.
$unusedVlan = if ((Get-Content -raw c:\config.txt) -match '(?ms)^999.*?(?=\r?\n\S|\Z)')
{ $Matches[0]}
# Split the string into an array of token by whitespace,
# remove all "," instances,
# and skip the first 3 tokens
# (the tokens *before* the port numbers, namely '999', 'Unused', 'active')
# The result is an *array* of all port numbers: @( 'Fa0/10', 'Fa0/11', ... )
$unusedPorts = (-split $unusedVlan) -replace ',' | Select-Object -Skip 3
# Output the array
$unusedPorts