While循環不會產生可以在流水線中繼續的輸出。我需要處理一個大的(很多GiB)文件。在這個微不足道的例子中,我想提取第二個字段,對它進行排序,然後只獲取唯一值。我對While循環沒有什麼瞭解,並通過管道推動事物?While循環不產生流水線輸出
在* NIX世界,這將是一個簡單的:
cut -d "," -f 2 rf.txt | sort | uniq
在PowerShell中,這將是不是很簡單。
源數據。
PS C:\src\powershell> Get-Content .\rf.txt
these,1,there
lines,3,paragraphs
are,2,were
腳本。
PS C:\src\powershell> Get-Content .\rf.ps1
$sr = New-Object System.IO.StreamReader("$(Get-Location)\rf.txt")
while ($line = $sr.ReadLine()) {
Write-Verbose $line
$v = $line.split(',')[1]
Write-Output $v
} | sort
$sr.Close()
輸出。
PS C:\src\powershell> .\rf.ps1
At C:\src\powershell\rf.ps1:7 char:3
+ } | sort
+ ~
An empty pipe element is not allowed.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : EmptyPipeElement
將導入-CSV表現得像獲取內容,並嘗試將整個文件讀入內存?如果是這樣,那將不會處理大文件。 – lit
@Liturgist我的理解是'Get-Content'(當沒有'-Raw'開關時調用)不會將整個文件讀入內存。如果你看到了這種行爲,那很可能是因爲你把它管道到'Sort-Object'('sort'是後者的別名)。看到我的答案爲什麼。 – briantist
對延遲迴復表示歉意。 'Import-Csv'將一次讀取一行文件。你不需要擔心做一個單獨的'Get-Content'。 https://technet.microsoft.com/library/2a767ced-0fc9-4896-a8f0-2c5bdee49910(v=wps.630).aspx – Nasir