sed命令 #
一、基本用法 #
bash
#!/bin/bash
# 替换第一个匹配
sed 's/old/new/' file.txt
# 替换所有匹配
sed 's/old/new/g' file.txt
# 替换指定行
sed '2s/old/new/' file.txt
# 直接修改文件
sed -i 's/old/new/g' file.txt
二、常用命令 #
| 命令 | 说明 |
|---|---|
| s | 替换 |
| d | 删除 |
| p | 打印 |
| a | 追加 |
| i | 插入 |
| c | 替换行 |
三、地址范围 #
bash
#!/bin/bash
# 指定行
sed '3d' file.txt # 删除第3行
sed '2,5d' file.txt # 删除2-5行
# 模式匹配
sed '/pattern/d' file.txt # 删除匹配行
sed '/start/,/end/d' file.txt
四、实战示例 #
bash
#!/bin/bash
# 删除空行
sed '/^$/d' file.txt
# 删除注释
sed '/^#/d' file.txt
# 多命令
sed -e 's/old/new/g' -e 's/foo/bar/g' file.txt
# 使用脚本文件
sed -f script.sed file.txt
下一步 #
你已经掌握了sed命令,接下来让我们学习 awk命令!
最后更新:2026-03-27