使用Powershell和Regex仅匹配第一个

时间:2019-02-27 09:39:11

标签: powershell

在我的设备配置中,它具有show running-config和start-up配置,它们都与第vty行配置相同,例如

show running-config

line vty 0 4
 access-class 20 in
 password 7 373737
 login authentication test
 exec-timeout 10
 transport input ssh
line vty 5 15
 access-class 20 in
 password 7 373737
 login authentication test
 exec-timeout 10

start-up config
line vty 0 4
 access-class 20 in
 password 7 373737
 login authentication test
 exec-timeout 10
 transport input ssh
line vty 5 15
 access-class 20 in
 password 7 373737
 login authentication test
 exec-timeout 10
 transport input ssh

我在下面编写了Powershell脚本和正则表达式,当我运行脚本时,它会输出四次。我只想匹配第一个匹配项,并且只输出running-config的结果,但不知道如何。有人可以帮忙吗?

$Line_VTY = Select-String -path c:\test\config.txt -Pattern "\sline\svty\s\d{1}\s\d{1,2} -Context 0,6

write-host $line_vty

并且输出显示

line vty 0 4
 access-class 20 in
 password 7 373737
 login authentication test
 exec-timeout 10
 transport input ssh
line vty 5 15
 access-class 20 in
 password 7 373737
 login authentication test
 exec-timeout 10
 transport input ssh
line vty 0 4
 access-class 20 in
 password 7 373737
 login authentication test
 exec-timeout 10
 transport input ssh
line vty 5 15
 access-class 20 in
 password 7 373737
 login authentication test
 exec-timeout 10
 transport input ssh

2 个答案:

答案 0 :(得分:0)

选择字符串将匹配所有内容,要获取第一个字符串,请将其通过管道传递到select-object

select-object -First 1

类似

Select-String -path ./config.txt -Pattern "\sline\svty\s\d{1}\s\d{1,2}" | select-object -First 1

或根据上下文获得

enter image description here

答案 1 :(得分:0)

Select-String提供了-List开关,每个输入文件仅找到 1 个匹配项:

Select-String -List -Path c:\test\config.txt -Pattern '\sline\svty\s\d{1}\s\d{1,2}' -Context 0,5

请注意,您将收到带有match information的单个输出对象:

  • .Line属性包含匹配的行。

  • .Context属性在其.PostContext属性中包含另外5条上下文行。

因此,如果要全部输出6条线 ,作为 strings ,请使用以下命令:

Select-String -List -Path c:\test\config.txt -Pattern '\sline\svty\s\d{1}\s\d{1,2}' -Context 0,5 |
  ForEach-Object { $_.Line; $_.Context.PostContext }