![](/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.