Powershell搜索特定的字符串,然后在其后面添加文本



我很确定这很容易做到,但我找不到答案。假设我有一个文本文件与一堆行在它。

下面文本文件的内容
dbuser=admin
dbpassword=

在Powershell中,我想找到字符串"dbpassword="并添加文字"password";就在=后面。解决方案我已经搜索-替换,但我不想替换行,只是想添加"密码"。

谁能分享Powershell代码是什么?

假设=字符之后的所有字符都是'password'。

Get-Content -Path '.bunchoflines.txt' |
ForEach-Object { $_ -match '^dbpassword=' ? 'dbpassword=password' : $_ }

不知道为什么要关心它是否被替换,但是您可以直接输出后面跟着密码的行。假设您想要更新文件,我将使用Set-Content来写入文件,并使用switch语句来读取文件。

$inputfile = 'pathtoinputfile.txt'
Set-Content -Path $inputfile -value $(
switch -Regex -File $inputfile {
'^dbpassword=' {"$($_)password"}
default {$_}
}
)

感谢大家的贡献,我最终找到了这个解决方案。

$config = Get-Content pathtofilesomefile.txt
$password = abcdef
$config -replace "dbpassword=.*",("dbpassword="+$password) |
Set-Content pathtofilesomefile.txt

最新更新