![](/img/trans.png)
[英]using Powershell, how can I find a specific line in a multi-line variable, then locate the 3rd word or value within the line
[英]PowerShell: How to find a word within a line of text and modify the data behind it
我正在寻找一种方法来在一段文本中找到一个带有值的单词,然后更新该值。 例子:
在文件中多次出现 'schema="anon" maxFileSize="??????" maxBufferSize="123"' 我想找到所有包含 maxFileSize 的行,然后更新未知值 ?????? 到 123456。
到目前为止,我想出了这个:
cls
$Files = "C:\temp1\file.config","C:\temp2\file.config"
$newMaxFileSize = "123456"
ForEach ($File in $Files) {
If ((Test-Path $File -PathType Leaf) -eq $False) {
Write-Host "File $File doesn't exist"
} Else {
# Check content of file and select all lines where maxFileSize isn't equal to 123456 yet
$Result = Get-Content $File | Select-String -Pattern "maxFileSize" -AllMatches | Select-String -Pattern "123456" -NotMatch -AllMatches
Write-Host $Result
<#
ROUTINE TO UPDATE THE SIZE
#>
}
}
然而,我不知道如何找到“maxFileSize”这个词,更不用说如何更新它背后的值了......
假设输入文件实际上是 XML,请使用以下 XPath 表达式来定位所有具有maxFileSize
属性(无论值如何)的节点:
# Parse input file as XML
$configXml = [xml](Get-Content $file)
# Use Select-Xml to find relevant nodes
$configXml |Select-Xml '//*[@maxFileSize]' |ForEach-Object {
# Update maxFileSize attribute value
$_.Node.SetAttribute('maxFileSize','123456')
}
# Overwrite original file with updated XML
$configXml.Save($file.FullName)
如果配置文件是某种没有现成可用的解析器的陈旧格式,请使用-replace
操作符在适当的地方更新值:
$Results = @(Get-Content $File) -creplace '(?<=maxFileSize=")[^"]*(?=")','123456'
上面使用的模式(?<=maxFileSize=")[^"]*(?=")
描述了:
(?<= # Positive look-behind assertion, this pattern MUST precede the match
maxFileSize=" # literal string `maxFileSize="`
) # Close look-behind
[^"]* # Match 0 or more non-" characters
(?= # Positive look-ahead assertion, this pattern MUST succeed the match
" # literal string `"`
) # Close look-ahead
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.