在软件开发中,统计代码行数(Lines of Code,LOC)是衡量项目规模和复杂度的重要指标之一。常见场景包括:评估项目工作量、衡量团队产出、检测重复代码、代码审查和质量分析等。下面介绍六种常见的统计代码行数方式。
一、使用 find 和 wc 命令统计代码行数
在 Linux/Unix 环境中,可以结合 find 和 wc 来快速统计项目中的代码行数。
示例命令
# 统计所有 .js 文件的行数
find . -name "*.js" | xargs wc -l
参数说明
find . -name "*.js":递归查找所有后缀为 .js 的文件xargs wc -l:统计每个文件的行数并求和
忽略目录和文件
find . -name "*.js" -not -path "./node_modules/*" | xargs wc -l
忽略注释和空行(示例:去掉以 // 开头和空行)
find . -name "*.js" | xargs grep -vE "^\s*(//|$)" | wc -l
二、使用 PowerShell 工具统计代码行数
在 Windows 环境下,可以使用 PowerShell 脚本统计代码行数。
示例命令
# 统计所有 .cs 文件的行数
Get-ChildItem -Recurse -Include *.cs | Get-Content | Measure-Object -Line
忽略目录
Get-ChildItem -Recurse -Include *.cs -Exclude *bin*,*obj* | Get-Content | Measure-Object -Line
忽略空行和注释
Get-ChildItem -Recurse -Include *.cs |
Get-Content |
Where-Object { $_ -notmatch '^\s*($|//)' } |
Measure-Object -Line
三、使用 Git 命令统计代码行数
Git 提供的 git ls-files 命令能列出版本库管理的文件,结合 wc、cat 等命令,就可以对代码行数进行统计。
1. 统计所有文件的行数
git ls-files | xargs wc -l
输出结果会显示每个文件的行数,并在最后一行给出 合计。
2. 只显示总行数
如果只需要总行数,不关心单个文件的统计,可以用以下两种方式:
git ls-files | xargs cat | wc -l
或:
git ls-files | xargs wc -l | awk '{total+=$1} END{print total}'
3. 指定文件类型
有时候只想统计某种类型的文件(如 .js、.py 等),可以在 git ls-files 中指定:
# 统计所有 .js 文件
git ls-files '*.js' | xargs wc -l
# 统计多个类型的文件(.js 和 .html)
git ls-files '*.js' '*.html' | xargs wc -l
4. 忽略某些文件类型
如果要排除某些文件(如 .md 文档),可以结合 grep:
git ls-files | grep -v '\.md$' | xargs wc -l
5. 指定目录下的文件
只统计某个目录(如 src/)下的 .js 文件:
git ls-files 'src/*.js' | xargs wc -l
6. 使用 grep -v 过滤目录
git ls-files | grep -v '^node_modules/' | xargs wc -l
如果要排除多个目录:
git ls-files | grep -vE '^(node_modules|dist|docs)/' | xargs wc -l
排除目录的同时,指定文件类型
git ls-files '*.vue' '*.js' | grep -vE '^(node_modules|uni_modules)/' | xargs wc -l
四、使用代码编辑器插件
现代 IDE(如 VS Code、IntelliJ IDEA、Eclipse 等)都提供代码统计插件:
VS Code: VS Code Counter 插件
使用命令 VSCodeCounter: Count lines in workspace.右键选中文件夹 Count lines in directory. IntelliJ IDEA: 内置统计功能
Eclipse: 通过插件 Metrics
优点:可视化强,支持语言识别,自动忽略注释和空行。 缺点:依赖开发工具,不适合自动化统计。
五、使用 jscpd 检测重复代码
jscpd 是一个常见的重复代码检测工具,也能间接统计代码规模。
安装
npm install -g jscpd
使用
jscpd --path .
它会输出:
文件总数代码行数重复比例
适合在 CI/CD 中集成,用于质量检测。
六、自己实现一个统计工具
如果需要更灵活的控制,可以自己实现一个脚本来统计代码行数。
Python 示例
import os
def count_lines(path, extensions, exclude_dirs=None):
total = 0
exclude_dirs = exclude_dirs or []
for root, dirs, files in os.walk(path):
if any(ex in root for ex in exclude_dirs):
continue
for file in files:
if file.endswith(tuple(extensions)):
with open(os.path.join(root, file), encoding="utf-8", errors="ignore") as f:
for line in f:
if line.strip() and not line.strip().startswith("//"):
total += 1
return total
print("代码行数:", count_lines(".", [".py", ".js"], ["node_modules", "venv"]))
此脚本支持:
忽略目录(如 node_modules、venv)忽略注释行和空行
总结
方式优点缺点适用场景find + wc简单快捷不能自动识别注释Linux/Mac 快速统计PowerShellWindows 下方便语法相对复杂Windows 环境Git 命令支持历史统计统计规则有限版本管理分析编辑器插件界面友好依赖 IDE本地开发统计jscpd可检测重复代码偏向质量分析CI/CD 质量检测自己实现灵活需要开发定制化需求
