在linux中,sed工具是一种功能强大的流编辑器,广泛用于文本处理。以下是关于sed工具使用的一些关键点和示例:
Sed工具的概述
Sed是一种流编辑器,它以行为单位进行处理。在处理过程中,sed将当前行存储在临时缓冲区中,称为“模式空间”(pattern space)。处理完后,缓冲区的内容被发送到屏幕。文件内容不会被改变,除非使用重定向存储输出。需要注意的是,sed命令默认不会修改原文件,除非使用-i参数。
Sed命令的基本结构
sed [参数] [命令] [文件]
常用参数
-
-f 脚本文件:使用指定的脚本文件处理输入文本。 -
-e 脚本:使用指定的脚本处理输入文本。 -
-n:仅显示处理后的行。
常用命令
-
a\\:在当前行下方插入文本。 -
i\\:在当前行上方插入文本。 -
d:删除选择的行。 -
s:替换指定字符。 -
p:打印模板块的行。 -
r file:从文件中读取行。 -
w file:将行写入文件。 -
c:替换当前行。
示例
-
默认显示所有内容
sed '/root/ROOT/p' /etc/passwd
仅显示发生改变的行:
sed -n '/root/ROOT/p' /etc/passwd
-
查看指定行
查看第10行:
sed -n '10p' /etc/passwd
查看5-10行:
sed -n '5,10p' /etc/passwd
-
字符替换
将文件中的第一个
root替换为ROOT:sed 's/root/ROOT/' /etc/passwd
替换所有
root为ROOT:sed 's/root/ROOT/g' /etc/passwd
从每行的第二个
root开始替换:sed 's/root/ROOT/2g' /etc/passwd
-
行替换
将文件的1-5行替换为
i very happy:sed '1,5c i very happy' test
替换以
root开头的行:sed '/^root/c\\root user login' /etc/passwd
-
定界符
使用
/作为定界符:sed 's/root/ROOT/g'
使用其他定界符,如
:或|:sed 's:root:ROOT:g' sed 's|root|ROOT|g'
当定界符出现在样式内部时,需要转义:
sed 's/\/root/\/ROOT/g'
-
删除操作
删除空白行:
sed '/^$/d' test
删除第2行:
sed '2d' test
删除第2行到末尾的所有行:
sed '2,$d' test
删除最后一行:
sed '$d' test
删除以
root开头的行:sed '/^root/d' test
删除包含
root的行:sed '/root/d' test
删除奇数行,显示偶数行:
sed '1~2d' test
-
多点编辑
使用
-e选项执行多条命令:sed -e '1,5d' -e 's/root/ROOT/g' /etc/passwd
-
从文件读入
将
file的内容插入到与test匹配的行之后:sed '/test/r file' filename
-
写入文件
将包含
test的行写入file:sed -n '/test/w file' example
-
插入操作
在以
test开头的行下方插入this is a test line:sed '/^test/a\\this is a test line' test sed '/^test/a this is a test line' test
在第2行之后插入
this is a test line:sed '2a\\this is a test line' test sed '2a this is a test line' test
在以
test开头的行上方插入this is a test line:sed '/^test/i\\this is a test line' test sed '/^test/i this is a test line' test
在第5行之前插入
this is a test line:sed '5i\\this is a test line' test sed '5i this is a test line' test
在所有行的行首和行尾添加
HEAD和TAIL:sed 's/^/HEAD/g' test sed 's/$/TAIL/g' test
在指定行的行首和行尾添加
HEAD和TAIL:sed '5s/^/HEAD/' test sed '5s/$/TAIL/' test
过滤指定行,然后在过滤行的行首和行尾添加
HEAD和TAIL:sed '/^ONBOOT/s/^/HEAD/' ifcfg sed '/^ONBOOT/s/$/TAIL/' ifcfg

相关文章










