我會親自更進一步。我想計算連續跟隨的行數。然後打印文件名,行數和行數本身。您可以按行數(候選人刪除?)對結果進行排序。 請注意,我的代碼不註釋行之間的空行數,所以這部分被認爲是註釋代碼兩大塊:
// int a = 10;
// int b = 20;
// DoSomething()
// SomethingAgain()
這裏是我的代碼。
$Location = "c:\codeishere"
$occurences = get-ChildItem $Location *cs -recurse | select-string '//.*;'
$grouped = $occurences | group FileName
function Compute([Microsoft.PowerShell.Commands.MatchInfo[]]$lines) {
$local:lastLineNum = $null
$local:lastLine = $null
$local:blocks = @()
$local:newBlock = $null
$lines |
% {
if (!$lastLineNum) { # first line
$lastLineNum = -2 # some number so that the following if is $true (-2 and lower)
}
if ($_.LineNumber - $lastLineNum -gt 1) { #new block of commented code
if ($newBlock) { $blocks += $newBlock }
$newBlock = $null
}
else { # two consecutive lines of commented code
if (!$newBlock) {
$newBlock = '' | select File,StartLine,CountOfLines,Lines
$newBlock.File, $newBlock.StartLine, $newBlock.CountOfLines, $newBlock.Lines = $_.Filename,($_.LineNumber-1),2, @($lastLine,$_.Line)
}
else {
$newBlock.CountOfLines += 1
$newBlock.Lines += $_.Line
}
}
$lastLineNum=$_.LineNumber
$lastLine = $_.Line
}
if ($newBlock) { $blocks += $newBlock }
$blocks
}
# foreach GroupInfo objects from group cmdlet
# get Group collection and compute
$result = $grouped | % { Compute $_.Group }
#how to print
$result | % {
write-host "`nFile $($_.File), line $($_.StartLine), count of lines: $($_.CountOfLines)" -foreground Green
$_.Lines | % { write-host $_ }
}
# you may sort it by count of lines:
$result2 = $result | sort CountOfLines -desc
$result2 | % {
write-host "`nFile $($_.File), line $($_.StartLine), count of lines: $($_.CountOfLines)" -foreground Green
$_.Lines | % { write-host $_ }
}
如果您有任何想法如何改進代碼,請發佈!我有一種感覺,我可以使用一些標準的cmdlet,代碼可以更短。
我不知道什麼?{$ _._ -match $ regex} | `在做,但這是似乎阻止我獲得結果的線。這是做什麼的? 此外,我不得不改變$ _。FileName和$ _。Line到$ FileName和$ Line來讓它運行 – 2009-06-09 20:29:50
@Macho:Typo ...將ix,應該只是$ _。 – Richard 2009-06-10 07:25:49
請注意其他答案:select-string已經捕獲了文件名和行號。 – Richard 2009-06-10 07:29:14