使用git统计代码行数

在windows平台下使用powershell

# 统计所有文件行数
git ls-files | ForEach-Object { Get-Content $_ | Measure-Object -Line } | Measure-Object -Property Lines -Sum

# 统计特定文件类型
git ls-files "*.ps1" | ForEach-Object { Get-Content $_ | Measure-Object -Line } | Measure-Object -Property Lines -Sum

linux脚本:Bash脚本 (保存为count_lines.sh)

#!/bin/bash
echo "=== 代码行数统计 ==="
echo "总文件数: $(git ls-files | wc -l)"
echo "总代码行数: $(git ls-files | xargs cat | wc -l)"
echo "非空行数: $(git ls-files | xargs cat | grep -v '^$' | wc -l)"
echo ""
echo "按文件类型统计:"
echo "Java: $(git ls-files "*.java" | xargs cat | wc -l) 行"
echo "Python: $(git ls-files "*.py" | xargs cat | wc -l) 行"
echo "JavaScript: $(git ls-files "*.js" | xargs cat | wc -l) 行"
echo "TypeScript: $(git ls-files "*.ts" | xargs cat | wc -l) 行"

windows脚本:PowerShell脚本 (保存为count_lines.ps1)

Write-Host "=== 代码行数统计 ===" -ForegroundColor Green

$files = git ls-files
Write-Host "总文件数: $($files.Count)"

$totalLines = 0
$files | ForEach-Object { 
    if (Test-Path $_) {
        $totalLines += (Get-Content $_).Count
    }
}
Write-Host "总代码行数: $totalLines"

# 按文件类型统计
$fileTypes = @("*.java", "*.py", "*.js", "*.ts", "*.html", "*.css")
foreach ($type in $fileTypes) {
    $matchingFiles = git ls-files $type
    if ($matchingFiles) {
        $typeLines = 0
        $matchingFiles | ForEach-Object { 
            if (Test-Path $_) {
                $typeLines += (Get-Content $_).Count
            }
        }
        Write-Host "$($type.Trim('*')): $typeLines 行"
    }
}


使用git统计代码行数
https://www.tab6.site/archives/shi-yong-gittong-ji-dai-ma-xing-shu
作者
tab
发布于
2025年10月15日
许可协议