sed Commandsed命令

Stream editor for filtering text用于过滤文本的流编辑器

What is sed?什么是sed?

sed stands for "stream editor". It performs text transformations on an input stream (a file or pipe). Unlike interactive editors, sed is non-interactive and perfect for automated text processing, search-and-replace operations, and complex text manipulations.

sed代表"stream editor"(流编辑器)。它对输入流(文件或管道)执行文本转换。与交互式编辑器不同,sed是非交互式的,非常适合自动化文本处理、搜索和替换操作以及复杂的文本操作。

Basic Usage基本用法

$ sed 's/old/new/' file.txt
# Replace first occurrence per line
$ sed 's/old/new/g' file.txt
# Replace all occurrences (global)
$ sed '5d' file.txt
# Delete line 5
$ sed 's/old/new/' file.txt
# 每行替换第一次出现
$ sed 's/old/new/g' file.txt
# 替换所有出现(全局)
$ sed '5d' file.txt
# 删除第5行

Common Options常用选项

Option选项 Full Name完整名称 Description描述 Example示例
-i in-place就地编辑 Edit files in place就地编辑文件 sed -i 's/foo/bar/g' file.txt
-n quiet安静模式 Suppress automatic printing抑制自动打印 sed -n '5p' file.txt
-e expression表达式 Add script to commands将脚本添加到命令 sed -e 's/a/b/' -e 's/c/d/'
-f file文件 Add script from file从文件添加脚本 sed -f script.sed file.txt

Common Commands常用命令

Command命令 Description描述 Example示例
s/pattern/replacement/ Substitute替换 sed 's/foo/bar/'
/pattern/d Delete matching lines删除匹配的行 sed '/error/d'
Nd Delete Nth line删除第N行 sed '5d'
Np Print Nth line打印第N行 sed -n '5p'
s/.*$// Delete to end of line删除到行尾 sed 's/.*$//' file.txt

Practical Scenarios实际场景

Replace All Occurrences in File替换文件中的所有出现

$ sed -i 's/old/new/g' file.txt
# Replace all occurrences and save
$ sed -i 's/old/new/g' file.txt
# 替换所有出现并保存

Delete Lines Matching Pattern删除匹配模式的行

$ sed '/^#/d' config.txt
# Remove all comment lines
$ sed '/^#/d' config.txt
# 删除所有注释行

Print Specific Line Range打印特定行范围

$ sed -n '10,20p' file.txt
# Print lines 10-20
$ sed -n '10,20p' file.txt
# 打印第10-20行

Memory Tricks记忆技巧

🌊 "sed" = stream editor - Edit text as it flows by!

🌊 "sed" = stream editor(流编辑器) - 在文本流动时编辑!

🔄 s/old/new/ = substitute - Replace pattern with replacement

🔄 s/old/new/ = substitute(替换) - 用替换内容替换模式

🌍 g = global - Replace all occurrences, not just first

🌍 g = global(全局) - 替换所有出现,不仅仅是第一次

💾 -i = in-place - Edit the file directly (be careful!)

💾 -i = in-place(就地) - 直接编辑文件(小心!)

🗑️ d = delete - Delete specified lines

🗑️ d = delete(删除) - 删除指定的行

🖨️ p = print - Print specified lines (use with -n)

🖨️ p = print(打印) - 打印指定的行(与-n一起使用)