【问题标题】:Replace string after a given string in Powershell在Powershell中给定字符串之后替换字符串
【发布时间】:2023-04-05 21:46:01
【问题描述】:

这是我的文件:

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

[Client]
local_port = 22

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

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

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

为了明确,我想改变port_nb =之后的东西,例如我想要的。

我怎样才能做到这一点?可能是按索引,但我不知道如何使用索引来替换... 谢谢!

【问题讨论】:

    标签: windows powershell file replace


    【解决方案1】:

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

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

    【讨论】:

    • 太完美了,没想到...谢谢 :) !
    • 考虑到空格并不总是在适当的位置,可能会更节省:(Get-Content -Path ssh_config.cfg -Raw) -replace "port_nb *= *\d+", "port_nb = 2589"跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-08
    • 2020-02-25
    • 2014-12-03
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 2017-03-06
    相关资源
    最近更新 更多