在Powershell中给定字符串之后替换字符串

时间:2019-07-25 13:38:19

标签: windows powershell file replace

这是我的文件:

[Server]
port_nb = 2222
dist_user = martin
dist_ip = 192.168.11.111

[Client]
local_port = 22

我想用Powershell将代码中给定字符串之后的字符串替换为var。

我不想使用 ((Get-Content -path ssh_config.cfg -Raw) -replace '2222','2589' 因为我对2222进行了硬编码,并且该值可以随机更改,所以我无法对=之后的值进行搜索,然后替换它。

这就是为什么我认为我必须首先搜索port_nb =,然后替换之后可以找到的字符串。

为清楚起见,我想根据自己的意愿来更改port_nb =之后的内容。

我该如何实现?按索引也许,但我找不到如何通过使用索引来使用替换... 谢谢!

1 个答案:

答案 0 :(得分:0)

一种选择是使用正则表达式模式而不是您的硬编码“ 2222”:

(Get-Content -Path ssh_config.cfg -Raw) -replace "port_nb = \d+", "port_nb = 2589"