簡體   English   中英

刪除PowerShell中特定行之后的所有行

[英]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不會退出管道,它會退出任何封閉循環foreachfordowhile語句),如果沒有,則退出整個腳本。

但是,您可以簡單地修改您的方法以使用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]
}

暫無
暫無

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

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