Linux 文本处理:grep、awk 与真正能完成工作的管道
发布: (2025年12月16日 GMT+8 06:31)
10 min read
原文: Dev.to
Source: Dev.to
请提供需要翻译的正文内容,我才能为您完成简体中文的翻译。
问题:手动搜索文件
您需要在一个 10,000 行的日志文件中查找所有错误信息。或者从系统文件中提取用户名。再或者统计特定 IP 地址在访问日志中出现的次数。
在编辑器中打开文件并手动搜索?这既慢又容易出错。
Linux 文本处理工具可以把这些任务变成一行命令完成。
cut 命令 – 提取列
cut 从每行中提取特定字符或字段。
按字符位置
# Get first character from each line
cut -c1 file.txt
# Get characters 1‑3
cut -c1-3 file.txt
# Get characters 1, 2, and 4
cut -c1,2,4 file.txt
实际示例 – 提取文件权限
ls -l | cut -c1-10
# Output: drwxr-xr-x, -rw-r--r--, etc.
awk 命令 – 模式扫描与处理
awk 在提取和操作字段(列)方面非常强大。
基本字段提取
# Print first column
awk '{print $1}' file.txt
# Print first and third columns
awk '{print $1, $3}' file.txt
# Print last column (NF = number of fields)
ls -l | awk '{print $NF}'
# Shows filenames from ls -l output
搜索并打印
# Find lines containing "Jerry" and print them
awk '/Jerry/ {print}' file.txt
# Or shorter:
awk '/Jerry/' file.txt
更改字段分隔符
# Use colon as delimiter (common in /etc/passwd)
awk -F: '{print $1}' /etc/passwd
# Output: list of all usernames
修改字段
# Replace second field with "JJ"
echo "Hello Tom" | awk '{$2="JJ"; print $0}'
# Output: Hello JJ
按长度过滤
# Get lines longer than 15 characters
awk 'length($0) > 15' file.txt
实际案例 – 提取 IP 地址
# Get IP addresses from access log
awk '{print $1}' /var/log/nginx/access.log
# Count unique IPs
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c
grep 命令 – 搜索文本
grep(global regular expression print)用于在文件或输出中搜索关键字。
基本搜索
# 在文件中查找关键字
grep keyword filename
# 在输出中搜索
ls -l | grep Desktop
常用选项
# 统计出现次数
grep -c keyword file.txt
# 忽略大小写
grep -i keyword file.txt
# 匹配:keyword、Keyword、KEYWORD
# 显示行号
grep -n keyword file.txt
# 输出示例:5:line with keyword
# 排除包含关键字的行(反向匹配)
grep -v keyword file.txt
实际案例 – 在日志中查找错误
# 查找所有错误行
grep -i error /var/log/syslog
# 统计错误数量
grep -i error /var/log/syslog | wc -l
# 查找错误但排除特定错误
grep -i error /var/log/syslog | grep -v "ignore_this_error"
egrep 命令 – 多关键字
egrep(或 grep -E)一次搜索多个模式。
# 搜索 keyword1 或 keyword2
egrep -i "keyword1|keyword2" file.txt
# 查找包含 error 或 warning 的行
egrep -i "error|warning" /var/log/syslog
sort 命令 – 字母顺序排序
# Sort alphabetically
sort file.txt
# Reverse sort
sort -r file.txt
# Sort by second field
sort -k2 file.txt
实际示例 – 按文件大小排序
# Sort files by size (5th column in ls -l)
ls -l | sort -k5 -n
# -n flag for numerical sort
uniq 命令 – 删除重复行
uniq 用于过滤重复的行。重要: 输入必须先排序。
# Remove duplicates
sort file.txt | uniq
# Count duplicates
sort file.txt | uniq -c
# Output: 3 line_content (appears 3 times)
# Show only duplicates
sort file.txt | uniq -d
实际示例 – 最常见的日志条目
# Find most common errors
grep error /var/log/syslog | sort | uniq -c | sort -rn | head -10
逐步说明
| 步骤 | 目的 |
|---|---|
grep error | 查找错误行 |
sort | 将相同的行归为一组 |
uniq -c | 计数每行出现的次数 |
sort -rn | 按计数排序(数值型,降序) |
head -10 | 显示前 10 条结果 |
wc 命令 – 统计行数、单词数、字节数
wc(word count)读取文件并报告计数。
# 统计行数、单词数、字节数
wc file.txt
# 输出: 45 300 2000 file.txt
# 仅行数
wc -l file.txt
# 仅单词数
wc -w file.txt
# 仅字节数
wc -c file.txt
实际示例
# 统计目录中的文件数
ls -l | wc -l
# 统计关键字出现的次数
grep keyword file.txt | wc -l
# 统计 Python 文件的总代码行数
find . -name "*.py" -exec wc -l {} \; | awk '{sum+=$1} END {print sum}'
比较文件 – diff
逐行比较
# Compare files
diff file1.txt file2.txt
# Output shows differences:
# line in file2
字节逐个比较 – cmp
# Compare files
cmp file1.txt file2.txt
# Output: first byte that differs
# No output if files are identical
使用管道组合命令
真正的威力来自于将命令串联起来。
示例 1:查找并计数
# How many users have /bin/bash as their shell?
grep "/bin/bash" /etc/passwd | wc -l
示例 2:前 5 大文件
ls -lh | sort -k5 -h -r | head -5
示例 3:提取并排序
# Get all usernames and sort them
awk -F: '{print $1}' /etc/passwd | sort
示例 4:搜索、提取、计数
# Find IP addresses that accessed /admin
grep "/admin" /var/log/nginx/access.log \
| awk '{print $1}' \
| sort \
| uniq -c \
| sort -rn
这显示了哪些 IP 最常访问 /admin。
示例 5:日志分析
# Find most common error types
grep -i error /var/log/app.log \
| awk '{print $5}' \
| sort \
| uniq -c \
| sort -rn \
| head -10
实际场景
场景 1:查找大文件
# Files larger than 100 MB
find / -type f -size +100M 2>/dev/null \
| xargs ls -lh \
| awk '{print $5, $NF}'
场景 2:监控活跃连接
# Count connections per IP
netstat -an | grep ESTABLISHED \
| awk '{print $5}' \
| cut -d: -f1 \
| sort \
| uniq -c \
| sort -rn
场景 3:检查登录失败尝试
# Count failed SSH attempts by IP
grep "Failed password" /var/log/auth.log \
| awk '{print $11}' \
| sort \
| uniq -c \
| sort -rn
场景 4:按目录查看磁盘使用情况
# Top 10 directories by size
du -h /var | sort -h -r | head -10
场景 5:提取电子邮件地址
# Find all email addresses in a file
grep -Eo '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}' file.txt \
| sort \
| uniq
常见模式
模式 1:搜索、提取、排序、计数
grep pattern file | awk '{print $2}' | sort | uniq -c | sort -rn
模式 2:过滤和处理
cat file | grep -v exclude_pattern | awk '{print $1}'
模式 3:多条件
egrep "error|warning" file | grep -v "ignore" | wc -l
快速参考
cut
cut -c1-3 file # 第1‑3字符
cut -d: -f1 file # 第一个字段(分隔符 :)
awk
awk '{print $1}' file # 第一列
awk -F: '{print $1}' file # 自定义分隔符
awk '/pattern/ {print}' file # 模式匹配
awk '{print $NF}' file # 最后一列
awk 'length($0) > 15' file # 行长度 > 15 个字符
grep
grep pattern file # 搜索
grep -i pattern file # 忽略大小写
grep -c pattern file # 计数匹配
grep -n pattern file # 显示行号
grep -v pattern file # 反向(排除)
egrep "pat1|pat2" file # 多模式
sort
sort file # 按字母顺序
sort -r file # 逆序
sort -k2 file # 按第二字段
sort -n file # 按数值
uniq
sort file | uniq # 删除重复项
sort file | uniq -c # 计数出现次数
sort file | uniq -d # 仅显示重复项
wc
wc file # 行数、单词数、字节数
wc -l file # 仅行数
wc -w file # 仅单词数
wc -c file # 仅字节数
diff / cmp
diff file1 file2 # 按行比较
cmp file1 file2 # 按字节比较
提高效率的技巧
技巧 1 – 使用管道而不是临时文件
# Instead of:
grep pattern file > temp.txt
sort temp.txt > sorted.txt
# Do:
grep pattern file | sort
技巧 2 – 将 grep 与 awk 结合使用
# Filter then extract
grep error log.txt | awk '{print $1, $5}'
技巧 3 – 使用 awk 代替多个 cut
# Instead of:
cut -d: -f1 file | cut -d- -f1
# Do:
awk -F: '{print $1}' file | awk -F- '{print $1}'
技巧 4 – 先在小样本上测试模式
# Test on first 10 lines
head -10 large_file.txt | grep pattern
关键要点
cut– 提取字符或字段。awk– 处理字段、模式匹配、计算。grep– 搜索模式。egrep/grep -E– 扩展正则表达式(多个模式)。sort,uniq,wc– 整理、去重并统计数据。diff/cmp– 比较文件(按行或按字节)。
使用管道 (|) 将这些工具组合起来,构建强大的单行命令行工作流。
**grep** – Search multiple patterns
**sort** – Order lines
**uniq** – Remove duplicates (must sort first)
**wc** – Count lines, words, bytes
**Pipes (|)** – Chain commands together
**diff / cmp** – Compare files
These commands aren't just for showing off; they solve real problems:
- Analyzing logs
- Extracting data
- Monitoring systems
- Processing reports
- Debugging issues
Master these tools and manual file searching becomes a thing of the past.
*What text‑processing task do you do most often? Share your go‑to command combinations in the comments.*```