随笔 - 6  文章 - 124  评论 - 1  阅读 - 13042

Linux sed 命令详解

简介

sed 的全称是:Stream Editor 流编辑器,在 Linux 中是一个强大的文本处理工具,可以处理文件或标准输入流。

基本语法

sed [options] 'command' file

通过管道传输入流:

echo "text" | sed 'command'

常用子命令

文本替换(s)

sed 's/old/new/' file

# s代表文本替换

# old表示被替换的旧文本

# new表示替换的新文本
  • 替换第一次匹配到的文本
sed 's/Linux/Unix/' file
  • 替换所有匹配到的文本(g)
sed 's/Linux/Unix/g' file
  • 替换时不区分大小写(i)
sed 's/linux/unix/gi' file

删除文本行(d)

sed '<n>d' file

# n代表第几行
  • 删除指定行的文本
sed '2d' file
  • 删除指定范围行的文本
sed '5,10d' file
  • 删除模式匹配到的行
sed '/pattern/d' file

追加文本(a)

sed '/pattern/a\new text' file
  • 在模式匹配到的文本下面添加一行文本
sed '/Linux/a\This is added text' file

插入文本(i)

sed '/pattern/i\new text' file
  • 在模式匹配到的文本上面添加一行文本
sed '/Linux/i\This is inserted text' file

替换指定行的内容(c)

sed '<n>c\new content' file

# n表示第几行
sed '3c\new content' file

打印与模式匹配的行文本(p)

sed -n '/pattern/p' file

# -n 表示抑制默认的打印输出,不加此选项会打印两遍
# p 表示打印文本
sed -n '/Linux/p' file

修改后覆盖源文件(-i)

sed -i 's/old/new/g' file
sed -i 's/Linux/Unix/g' file

同时执行多个 sed 子命令(-e)

使用 -e 选项或把命令放在文件中

sed -e 's/old/new/' -e '/pattern/d' file

新建一个文件,sed_commands.sed

s/old/new/
5,10d

通过 -f 指定 sed 命令文件

sed -f sed_commands.sed file

替换指定行模式匹配到的文本

sed '3s/old/new/' file

删除空白行

sed '/^$/d' file

# ^表示行首,$表示行尾
# ^$合在一起,就表示行首和行尾之间没有任何内容,即空白行

添加行号

sed = <file> | sed 'N;s/\n/\t/'

# 第一步:sed = <file> 会生成行号,且打印如下的文本格式:
# 1
# Line 1 content
# 2
# Line 2 content

# 第二步:通过 | 管道传到下一个sed命令

# 第三步:N子命令合并当前行和下一行的内容,如下:
# 1\nLine 1 content

# 第四步:替换 \n 为 \t,如下:
# 1\tLine 1 content

# 最终输入结果:
# 1   Line 1 content
# 2   Line 2 content

提取指定行范围的文本

sed -n '5,10p' file

# 打印第5到第10行的文本

替换指定行范围的文本

sed '5,10s/old/new/g' file

# 替换仅在第5到第10行模式匹配的文本

移除行尾的空格

sed 's/[ \t]*$//' file

# [ \t] 表示匹配空格或者tab(\t)
# * 表示匹配0个或多个
# $ 表示行尾
# // 表示替换成空

同时操作多个文件

sed 's/old_string/new_string/g' filename1.txt filename2.txt

结合 find 命令操作

find /file -type f -exec sed -i 's/old_string/new_string/g' {} \;

操作后追加到新文件

sed -n 's/pattern/p' logfile.log > extracted_data.txt

多种转义字符的使用

  • 使用反斜杠 \
sed 's/\/old\/path/\/new\/path/' file
  • 使用竖线或者叫管道符号 |
sed 's|/old/path|/new/path|' file
posted on   我是唐青枫  阅读(111)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示