使用powershell 2删除一行文本和接下来的0到5行 [英] Remove a line of text and the next 0 to 5 lines with powershell 2
问题描述
我正在使用 powershell,想根据匹配删除一行文本,然后在匹配行之后删除一定数量的行.我有以下代码将删除具有匹配项的当前行.如何删除下一行?
I am using powershell and would like to delete a line of text based on a match and then a certain number of lines after the line with the match. I have the following code which will delete the current line with a match. How do I remove the next line(s)?
获取内容 $filePath |?{$_ -notmatch "`f"} |设置内容 $outPath
Get-Content $filePath | ? {$_ -notmatch "`f"} | Set-Content $outPath
推荐答案
即使这更长,但如果您有更复杂的规则"来确定要删除哪一行,它可能是一个有用的基础.(不过我更喜欢@mjolinor 的回答)
Even though this is longer, it may be a useful base if you have more complex "rules" to determine which line to remove. (I prefer @mjolinor's answer though)
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[String]$Source,
[Parameter(Mandatory=$true)]
[String]$Target,
[Parameter(Mandatory=$true)]
[Int32]$Lines
)
$LinesLeftToRemove = 0
$TargetContent = @()
(Get-Content $Source) | % {
If($_ -notmatch "`f") {
$LinesLeftToRemove = $Lines + 1
}
If($LinesLeftToRemove -GT 0) {
$LinesLeftToRemove--
} Else {
$TargetContent += $_
}
}
Set-Content $Target $TargetContent
请注意,这应该放在 SomeScript.ps1
文件中并像这样使用:
Note that this should be put in a SomeScript.ps1
file and used like this:
.\SomeScript.ps1 -Source .\Source.txt -Target .\Target.txt -Lines 5
这篇关于使用powershell 2删除一行文本和接下来的0到5行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!