[英]PowerShell Get-Content Foreach-object to replace the current line with a value from the next
I'm looking to replace a value in the current line with a value from the next line using PowerShell. 我正在寻找使用PowerShell将下一行的值替换当前行中的值。 Something like:
就像是:
gci | foreach {(gc $_.FullName) | foreach-object {
$a = #Here I want to use a regex to strip the ProductId from the next line
$_ -replace 'In Stock', "[[Availability ProductId=$a]]" }}
Can this be done? 能做到吗?
Not directly inside the ForEach-Object
, no. 不直接在里面
ForEach-Object
,没有。 You can cheat a little: 你可以骗一点:
$x = $null
Get-Content c:\mypath\file.htm <# who puts files there? #> |
ForEach-Object {
if ($x -eq $null) {
$x = $_
} else {
$x -replace 'This Value', $_ # or whatever you need from the next line
}
}
Another way is to just use the normal way: 另一种方法是只使用正常方式:
$lines = Get-Content c:\mypath\file.htm
$replacedLines = $(
for ($i = 0; $i -lt $lines.Length - 1; $i++) {
$lines[$i] -replace 'This Value', $lines[$i+1]
}
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.