[英]Delete all lines after a specific line in PowerShell
我有這個.txt
文件
ROTHSCHILD = 81; // Fondation Adolphe de Rothschild , 2019
ONCOPOLE = 82; // Oncopole - Toulouse , 2019
GHRMSA = 83; // GHR Mulhouse Sud-Alsace , 2019
CHDN = 84; // CH du Nord - Luxembourg , 2019
CAEN = 85; // CHU de Caen , 2019
MONTELIMAR = 86; // , 2019
PUYENVELAY = 87; // , 2019
我想刪除所有行
CHDN = 84; // CH du Nord - Luxembourg , 2019
我怎樣才能做到這一點 ?
我試過這個:
get-content txt.txt | % {$_ ; if($_ -eq "CHDN = 84; // CH du Nord - Luxembourg , 2019") {break }}
但是中斷我的程序,我該怎么做?
您可能需要每次都做一些測試。 我會像這樣使用Do..Until
循環:
$txtData = get-content txt.txt
$stophere = 'CHDN = 84; // CH du Nord - Luxembourg , 2019'
$ctr = 0
Do
{
$txtData[$ctr++] #Prints data line and increments counter
} Until ($txtData[$ctr] -eq $stophere)
但
break
結束了我的程序
原因是管道中的break
不會退出管道,它會退出任何封閉循環( foreach
、 for
、 do
和while
語句),如果沒有,則退出整個腳本。
但是,您可以簡單地修改您的方法以使用foreach
循環,其中break
可以按預期工作:
# The last line to include in the output.
$stopLine = 'CHDN = 84; // CH du Nord - Luxembourg , 2019'
# Output all lines up to and including the stop line.
# Simply assign to a variable to capture all output lines:
# $linesOfInterest = foreach ($line ...) { ... }
# Or wrap in $(...) to send to a file.
# $(foreach ($line ...) { ... }) | Set-Content ...
foreach ($line in Get-Content file.txt) {
$line
if($line -eq $stopLine) {break }
}
或者,使用基於正則表達式的解決方案將所有感興趣的行捕獲為單個多行字符串(如果需要,您可以將其拆分為帶有-split '\\r?\\n'
):
# The last line to include in the output.
$stopLine = 'CHDN = 84; // CH du Nord - Luxembourg , 2019'
# Use the -match operator with a regex that that captures everything
# from the beginning of the the file through the stop line, inclusively.
if ((Get-Content -Raw file.txt) -match '(?sm).*^{0}$' -f [regex]::Escape($stopLine)) {
# Output what was captured.
# Append -split '\r?\n' to split into an array of lines.
$Matches[0]
}
(?sm)
設置內聯正則表達式選項s
(使.
匹配換行符)和m
(使^
和$
匹配各行的結尾和開頭)
.*
匹配任何字符序列,包括無
^{0}$
匹配轉義的停止行(通過[regex]::Escape()
,以確保它按字面匹配),其中{0}
是被-f
替換的轉義行的占位符, 字符串格式化操作符
如果正則表達式匹配運算符-match
成功,它會填充自動$Matches
變量,其0
條目包含正則表達式完全匹配的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.