簡體   English   中英

使用PowerShell從文件中刪除特定文本

[英]Delete specific text from a file with PowerShell

我需要刪除/替換寫在更多行上並在文本行之間具有空白行的特定文本。

例如:

some text

text 1

other text

text 1

我需要刪除:

other text

text 1

結果將是:

some text

text 1

現在我有這個: (Get-Content file.txt) -notmatch "other text r ntext 1" | Out-File file.txt (Get-Content file.txt) -notmatch "other text r ntext 1" | Out-File 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM