查找包含“ string_a”的行,然后替换匹配的“ string_b”

我有一个要在Powershell中 sed 的json配置。这是config.json中的条目:

"gateway.public.host": "http://placeholder.ourdomain.com",

我想找到与字符串gateway.public.host匹配的行,但是我想在该行上替换单词placeholder

我在Powershell上找到的大多数示例都是找到一个匹配项并替换该匹配项。

linxierhebei 回答:查找包含“ string_a”的行,然后替换匹配的“ string_b”

在这里,正则表达式方法很明显。从一行的开头一直到“占位符”匹配所有内容,并用捕获组替换捕获组后保留文本的其余部分。

(Get-Content $file) -replace "(.*gateway.public.host.*)placeholder",'$1ReplacementText'

许多其他正则表达式也将在这里工作。


不过,我们还可以在PowerShell中使用cmdlet ConvertFrom-JsonConvertTo-Json

中的 power
$json = '{
    "gateway.public.host": "http://placeholder.ourdomain.com"
}'

$jsonObject = $json | ConvertFrom-Json
$jsonObject."gateway.public.host" = $jsonObject."gateway.public.host" -replace "placeholder","holdplacer"
$jsonObject | ConvertTo-Json -Depth 5

哪个会帮到您

{
    "gateway.public.host":  "http://holdplacer.ourdomain.com"
}

是的,我要承认那里还有更多代码。使用此方法,可以使代码更整洁,具体取决于您的开始以及最终的目标。

,

替换是SED等效项的一种。看到您是Powershell的新手,我会选择第一种方法。

如果您的情况确实如此:

$Json = Get-Content filename.json
$Json = $Json -replace ("`"gateway.public.host`": `"http://placeholder.ourdomain.com`"","`"gateway.public.host`": `"http://newvalue.ourdomain.com`"")

$Json | Set-Content filename.json -Force

或者您可以单行完成

(Get-Content filename.json).replace("`"gateway.public.host`": `"http://placeholder.ourdomain.com`"","`"gateway.public.host`": `"http://newvalue.ourdomain.com`"") | Set-Content filename.json

在Powershell中,catget-content的别名,因此,如果您想“感觉”更多的Linux,甚至可以这样做:

cat filename.json | %{$_ -replace "`"gateway.public.host`": `"http://placeholder.ourdomain.com`"","`"gateway.public.host`": `"http://newvalue.ourdomain.com`""} | Set-Content filename.json
本文链接:https://www.f2er.com/3140558.html

大家都在问