簡體   English   中英

使用 powershell 將文本文件中的特定行復制到單獨的文件

[英]Copy specific lines from a text file to separate file using powershell

我正在嘗試從以%%開頭的輸入文件中獲取所有行,然后使用 powershell 將其粘貼到輸出文件中。

使用了以下代碼,但是我只得到輸出文件中以%%開頭的最后一行,而不是所有以%%開頭的行。

我剛開始學習powershell,請幫忙

$Clause = Get-Content "Input File location"
$Outvalue = $Clause | Foreach { 
    if ($_ -ilike "*%%*")
    {
        Set-Content "Output file location" $_
    }
}

對於小文件,Get-Content 很好。 但是,如果您開始嘗試對較重的文件執行此操作,Get-Content 會占用您的內存並讓您懸而未決。

對於其他 Powershell 初學者來說,保持它非常簡單,你會得到更好的覆蓋(並具有更好的性能)。 所以,像這樣的事情可以完成這項工作:

$inputfile = "C:\Users\JohnnyC\Desktop\inputfile.txt"
$outputfile = "C:\Users\JohnnyC\Desktop\outputfile.txt"

$reader = [io.file]::OpenText($inputfile)
$writer = [io.file]::CreateText($outputfile)

while($reader.EndOfStream -ne $true) {
    $line = $reader.Readline()
    if ($line -like '%%*') {
        $writer.WriteLine($line);
    }
}

$writer.Dispose();
$reader.Dispose();

您正在循環文件中的行,並將每一行設置為文件的全部內容,每次都覆蓋前一個文件。

您需要切換到使用Add-Content而不是Set-Content ,這將附加到文件,或者將設計更改為:

Get-Content "input.txt" | Foreach-Object { 
    if ($_ -like "%%*") 
    {
        $_     # just putting this on its own, sends it on out of the pipeline
    }
} | Set-Content Output.txt

您更通常將其寫為:

Get-Content "input.txt" | Where-Object { $_ -like "%%*" } | Set-Content Output.txt

在 shell 中,你可以這樣寫

gc input.txt |? {$_ -like "%%*"} | sc output.txt

過濾整個文件,然后將所有匹配的行一次性發送到 Set-Content,而不是為每一行單獨調用 Set-Content。

注意。 PowerShell是在默認情況下不區分大小寫,所以-like-ilike行為相同。

暫無
暫無

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

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