脚本怎样统计文件行数

wen 实用脚本 33

本文目录导读:

脚本怎样统计文件行数

  1. Linux/Mac 系统
  2. Windows 系统
  3. Shell 脚本示例
  4. Python 脚本
  5. 注意事项

我可以为您提供多种统计文件行数的方法,适用于不同操作系统和需求场景:

Linux/Mac 系统

使用 wc 命令(最常用)

# 统计单个文件
wc -l filename.txt
# 统计多个文件
wc -l file1.txt file2.txt
# 统计所有 .txt 文件
wc -l *.txt
# 只显示行数,不显示文件名
wc -l < filename.txt

使用 awk 命令

# 统计文件行数
awk 'END {print NR}' filename.txt
# 统计多个文件
awk 'END {print FILENAME, NR}' file1.txt file2.txt

使用 sed 命令

# 统计文件行数
sed -n '$=' filename.txt

Windows 系统

使用 PowerShell

# 统计单个文件
(Get-Content filename.txt).Count
# 或者使用更高效的方法
(Get-Content filename.txt | Measure-Object -Line).Lines
# 统计多个 txt 文件
Get-ChildItem *.txt | ForEach-Object { 
    $lines = (Get-Content $_.FullName).Count
    Write-Host "$($_.Name): $lines lines"
}

使用命令提示符 (CMD)

# 统计文件行数(需要 find 命令)
find /v /c "" filename.txt
# 或使用 type 和 find 组合
type filename.txt | find /v /c ""

Shell 脚本示例

基础脚本

#!/bin/bash
# 统计指定文件的行数
count_lines() {
    local file="$1"
    if [ -f "$file" ]; then
        lines=$(wc -l < "$file")
        echo "$file: $lines 行"
    else
        echo "文件不存在: $file"
    fi
}
# 调用函数
count_lines "example.txt"

批量统计脚本

#!/bin/bash
# 统计当前目录下所有 .log 文件的行数
echo "文件行数统计报表"
echo "=================="
total=0
for file in *.log; do
    if [ -f "$file" ]; then
        lines=$(wc -l < "$file")
        printf "%-30s %5d 行\n" "$file" "$lines"
        total=$((total + lines))
    fi
done
echo "=================="
printf "%-30s %5d 行\n" "总计" "$total"

Python 脚本

简单版本

def count_lines(filename):
    try:
        with open(filename, 'r', encoding='utf-8') as f:
            return sum(1 for line in f)
    except FileNotFoundError:
        return f"文件 {filename} 不存在"
# 使用示例
print(count_lines("example.txt"))

批量统计版本

import os
def count_lines_in_directory(directory, extension=".txt"):
    """统计指定目录下所有特定扩展名的文件行数"""
    file_counts = {}
    total_lines = 0
    for filename in os.listdir(directory):
        if filename.endswith(extension):
            filepath = os.path.join(directory, filename)
            with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
                lines = sum(1 for line in f)
                file_counts[filename] = lines
                total_lines += lines
    return file_counts, total_lines
# 使用示例
counts, total = count_lines_in_directory(".", ".txt")
for file, lines in counts.items():
    print(f"{file}: {lines} 行")
print(f"总计: {total} 行")

注意事项

包含空行和空白

# 统计非空行(忽略空行和仅包含空白字符的行)
grep -c -v '^\s*$' filename.txt
# 统计非空白行(更严格)
grep -c '[^[:space:]]' filename.txt

大文件处理

对于非常大的文件,使用 wc -l 是最有效的方法,因为它不需要将整个文件读入内存。

性能比较(从快到慢)

  1. wc -l - 最快
  2. awk 'END {print NR}' - 较快
  3. sed -n '$=' - 中等
  4. Python/PowerShell 脚本 - 较慢(适合复杂处理)

选择哪种方法取决于您的具体需求、操作系统和文件大小,对于日常使用,wc -l 是最简单高效的选择。

抱歉,评论功能暂时关闭!