简而言之,
我需要在一个长文件中找到一个特定行,该文件以“set ip”开头,并以一些我需要替换的参数继续。该行在文件中多次出现,因此我需要在2条特定行之间找到它。
更长的故事:
我们很快将为我们的办公室配置许多FortiGate防火墙,大多数设置,策略等将是相同的,但是外部IP会更改,其他一些地址也会更改等。
因此,我正在尝试制作一个Powershell脚本,该脚本将采用现有配置(可能会更改)并找到我需要的特定行并替换它们。
我尝试使用正则表达式,但无法使其在多行上对我有效。
基本上作为引用,我需要在以下部分中找到“set ip”:
config system interface
edit "wan1"
set vdom "root"
set ip 7.7.7.7 255.255.255.252
set allowaccess ping https ssh
set ident-accept enable
set type physical
set scan-botnet-connections block
set alias "WAN1"
set role wan
set snmp-index 1
next
(为安全起见,更改了IP)等等。
到目前为止,我得到的是:
get-content .\Fortigate.conf | select-string -pattern "^#","set uuid " -notmatch
遗憾的是,我没有尝试剪切那部分文本以仅在其中搜索有效。
例如使用正则表达式,我尝试过:
get-content .\Fortigate.conf | select-string -pattern "^#","set uuid " -notmatch | select-string -Pattern '(?m)edit "wan1".*?end'
最佳答案
对于此问题,我不会尝试对多行进行正则表达式,而是采用PowerShell方式“对管道的中间部分实现”并记住信息,例如:
阅读每一行(如果您编写cmdlet,请使用 process
method部分):
get-content .\Fortigate.conf | ForEach {...
记住当前的
edit
部分:$Wan = ($_ | Select-String 'edit[\s]+"(.*)"').Matches.Groups[1].Value
在(
set
)部分中捕获特定的edit
:$SetIP = ($_ | Select-String 'set[\s]+ip[\s]+(.*)').Matches.Groups[1].Value
根据值和部分做出决定,例如:
If ($Wan -eq $MyWan) {
if (($SetIP -Split "[\s]+") -Contains $MyIP) {...
将您的新字符串条目(中间)放在管道上:
Write-Output " set ip $MyNewIP"
或保留原始字符串条目:
Else {Write-Output $_}
关于regex - 需要使用PowerShell从长配置文件中搜索一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50270218/