使用 PowerShell 从文件中删除特定文本

Delete specific text from a file with PowerShell

我需要 delete/replace 写在更多行上并且在文本行之间有空白行的特定文本。

例如:

some text

text 1

other text

text 1

我需要删除:

other text

text 1

结果将是:

some text

text 1

现在我有这个: (获取内容 file.txt)-notmatch "other text<code>rntext 1" |输出文件 file.txt

有多种方法可以解决这个问题。

抓取文本文件的前三行:

(Get-Content File.txt)[0..2]

选择要输出的字符串:

((Get-Content File.txt -raw) | Select-String -pattern "(?s)some text.*?text 1").matches.value

判断坏行的行号并排除:

$File = Get-Content File.txt
$FirstBadLine = $File.IndexOf("other text")
$LastBadLine = ($file | select -skip $firstbadline).IndexOf("text 1")+$firstbadline
$file[0..($firstbadline-1)],$file[($lastbadline+1)..$file.count]

确定第一个坏行并从那里跳过已知数量的行:

$File = Get-Content File.txt
$NumberOfBadLines = 5
$FirstBadLine = $File.IndexOf("other text")
$file[0..($firstbadline-1)+($firstbadline+$NumberOfBadLines)..$file.count] | Set-Content File.txt