【问题标题】:Delete specific text from a file with PowerShell使用 PowerShell 从文件中删除特定文本
【发布时间】:2019-03-13 08:37:55
【问题描述】:

我需要删除/替换写在更多行上并且在文本行之间有空白行的特定文本。

例如:

some text

text 1

other text

text 1

我需要删除:

other text

text 1

结果将是:

some text

text 1

现在我有这个: (Get-Content file.txt) -notmatch "other textrntext 1" | Out-File file.txt

【问题讨论】:

  • 不一样。我需要删除一个有空行的部分。
  • 您错过了显示到目前为止的代码。您可能会阅读以下帮助 How do I ask a good question?How to create a Minimal, Complete, and Verifiable example
  • 该示例应该可以帮助您入门...使用带有 -raw 参数的 get-content cmdlet,然后您可以在 select-string 的 -pattern 参数中使用 \r\n 来匹配换行符。正如 Olaf 所说,您应该提供一些代码。
  • 现在我有这个:(Get-Content file.txt) -notmatch "other textrntext 1" |输出文件 file.txt 。它不是这样工作的,我使用“rn”的方式有问题。

标签: powershell text-manipulation


【解决方案1】:

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

抓取文本文件的前三行:

(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

【讨论】:

  • 我试着举一个更简单的例子。我所拥有的是一个包含很多行的文件,我需要删除一个包含 5 行的部分(3 行带有文本,2 行之间有 2 个空行)。我不知道这些线的编号。
  • 我认为我的最后一个例子可以做你想做的事。
  • 你的最后一个例子救了我。我知道第三行和第五行,我搜索了第三行并做了 $firstBadLine-2。谢谢!
猜你喜欢
  • 2021-11-01
  • 2022-11-14
  • 1970-01-01
  • 2018-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多