在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

相关文章
以上就是Linux中sed工具的使用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号