Skip to main content

文本处理与搜索

查看文本内容​

cat file                # 输出全部内容
cat -n file # 带行号
less file # 分页查看(方向键翻页,q 退出,/ 搜索)
more file # 简单分页(只能下翻)
head -n 20 file # 前 20 行
head -100 file # 前 100 行
tail -n 20 file # 后 20 行
tail -f file # 实时跟踪追加的内容(看日志神器)
wc -l file # 行数
wc -w / -c # 单词数 / 字节数
rev file # 每行反转输出

grep 搜索​

grep keyword file       # 匹配行
grep -i keyword file # 忽略大小写
grep -r keyword dir/ # 递归搜索目录
grep -n keyword file # 显示行号
grep -v keyword file # 反向匹配(排除)
grep -c keyword file # 只统计匹配行数
grep -E "a|b" file # 扩展正则(等价 egrep)
grep -w word file # 全词匹配
grep -l keyword dir/* # 只列出含匹配的文件名

# 别名建议(加进 ~/.bashrc)
alias grep='grep --color=auto'

find / locate 找文件​

find /path -name "*.log"             # 按名字查找
find / -name "nginx.conf" 2>/dev/null# 全盘查找忽略错误
find /var/log -type f -mtime +7 # 7 天前修改的文件
find / -size +100M # 大于 100MB 的文件
find / -user root # 查找属主为 root 的文件
find . -type d -name node_modules # 找目录
# 组合并执行
find . -name "*.tmp" -exec rm {} \; # ⚠️ 删除所有 .tmp
find . -perm 777 # 查找权限过宽的文件

locate nginx.conf # 基于数据库快速查找(先运行 updatedb)

定位命令​

which nginx            # 命令所在路径(PATH 内)
whereis nginx # 命令及 man 帮助位置
type -a ls # 命令类型(alias/内置/外部)

sed 流编辑​

sed -n '2,5p' file     # 打印 2-5 行
sed -n '10p' file # 打印第 10 行
sed 's/foo/bar/g' file # 全局替换并输出到屏幕
sed -i 's/foo/bar/g' file # 直接修改文件 ⚠️
sed -n '/error/p' log # 打印含 error 的行
sed '/^#/d' file # 删除注释行(# 开头)
sed 's/^/>> /' file # 行首加前缀

awk 文本分析​

awk '{print $1}' file        # 打印每行第一列
awk '{print $1, $NF}' file # 第一列和最后一列
awk -F: '{print $1}' /etc/passwd # 按冒号分割
awk '/error/{print NR": "$0}' log # 含 error 的行号与内容
awk '{sum+=$5} END{print sum}' file # 第五列求和
awk 'NR>=2 && NR<=10{print}' file # 打印 2-10 行

排序去重计数​

sort file               # 排序
sort -u file # 排序并去重
sort -n -k2 file # 按第 2 列数字排序
sort -rn # 数字逆序(配合 du 用)
uniq # 相邻去重
sort file | uniq -c # 统计每行出现次数(先 sort 再 uniq)
sort access.log | uniq -c | sort -rn # 访问日志 Top IP

字段截取与变换​

cut -d: -f1 /etc/passwd # 冒号分隔取第一列
cut -c1-5 file # 取每行前 5 个字符
tr 'a-z' 'A-Z' < file # 转大写
tr -d '\r' < win.txt > unix.txt # 去掉 Windows 换行的 \r
paste a.txt b.txt # 按列拼接
join a.txt b.txt # 按公共列关联
diff a b # 比较两个文件
diff -u a b # 统一格式(patch 通用)

xargs 批量处理​

find . -name "*.log" | xargs grep error   # 批量搜索
find . -type f | xargs -n 50 rm # 每 50 个一批删除 ⚠️
echo "a b c" | xargs -n1 echo # 每参数执行一次

常用正则速查​

元字符含义
.任意字符
*重复 0 次或多次
+重复 1 次或多次(扩展正则)
?0 或 1 次(扩展正则)
^行首
$行尾
[abc]字符集合
[^a]非 a
\d \w \s数字 / 单词 / 空白(部分工具)
{n,m}重复 n 到 m 次