가장 간단한 방법으로 현재 디렉토리에서 대부분의 행이있는 5 개의 파일을 얻는 방법은 무엇입니까?
Jan 09 2021
"The Pragmatic Programmer"의 "변환 프로그래밍"장에 이러한 쉘 명령이 있습니다.
그 기능은 현재 디렉토리에서 가장 많은 행이있는 5 개의 파일을 나열하는 것입니다.
$ find . -type f | xargs wc -l | sort -n | tail -6 | head -5
470 ./debug.pml
470 ./test_to_build.pml
487 ./dbc.pml
719 ./domain_languages.pml
727 ./dry.pml
나는 PowerShell로 똑같은 일을하려고하는데 ,하지만 너무 장황 해 보인다
(Get-ChildItem .\ | ForEach-Object {$_ | Select-Object -Property 'Name', @{label = 'Lines'; expression = {($_ | Get-Content).Length}}} |Sort-Object -Property 'Lines')|Select-Object -Last 5
더 간단한 방법이있을 것이라고 믿지만 생각할 수 없습니다.
PowerShell을 사용하여 가장 간단한 방법으로 현재 디렉터리에있는 대부분의 줄이있는 파일을 가져 오는 방법은 무엇입니까?
물론 길이를 줄이기 위해 사용자 지정 별칭 및 약어를 사용할 필요는 없습니다. 더 간결 해 보이지만 가독성이 떨어집니다.
답변
2 iRon Jan 09 2021 at 20:05
Get-Content * | Group-Object PSChildName | Select-Object Count, Name |
Sort-Object Count | Select-Object -Last 5
1 if_ok_button Jan 10 2021 at 09:02
드디어 만족스러운 답을 찾았습니다!
파이프 라인 연산자 3 개 사용, 쉘 5 개 사용!
게다가 우리가 얻는 것은 더 확장 가능한 작업에 사용할 수있는 개체입니다.
나는 리눅스 쉘보다 기분이 좋다.
dir -file | sort {($_ | gc).Length} | select -l 5
pwnosh Jan 09 2021 at 16:42
Linq가있는 File.ReadLines 또는 Count 속성이있는 File.ReadAllLines를 사용해보십시오.
File.ReadLines
Get-ChildItem .\ -File |
Select-Object -Property Name, @{n='Lines'; e= {
[System.Linq.Enumerable]::Count([System.IO.File]::ReadLines($_.FullName))
}
} | Sort-Object -Property 'Lines' -Descending | Select-Object -First 5
File.ReadAllLines
Get-ChildItem .\ -File |
Select-Object -Property Name, @{n='Lines'; e= {
[System.IO.File]::ReadAllLines($_.FullName).Count
}
} | Sort-Object -Property 'Lines' -Descending | Select-Object -First 5
Theo Jan 09 2021 at 18:35
빠른 접근 방식은 다음을 사용하는 것입니다 switch -File
.
$files = (Get-ChildItem -File ).FullName $result = foreach ($file in $files) {
$lineCount = 0 switch -File $file {
default { $lineCount++ } } [PsCustomObject]@{ File = $file
Lines = $lineCount } } $result | Sort-Object Lines | Select-Object -Last 5