本文共 1645 字,大约阅读时间需要 5 分钟。
sed 是最早开始支持正则表达式的工具之一,能够以非交互方式编辑文件。通过 sed,用户可以轻松完成文件的增、删、改、查等操作。以下是 sed 的基本操作和常用命令的详细说明。
sed 的命令格式为:
sed [options] ‘command’ file(s)sed [options] -f scriptfile file(s)
其中,options 是 sed 的常用选项,command 是具体的 sed 命令,file(s) 是需要处理的文件路径。
以下是 sed 的常见操作指令:
sed 提供多种定位方法:
打印文件内容:
sed -n 'p' /etc/hosts
该命令将仅显示文件的内容,每行打印一次。
显示文件的第 1 行或第 2 行:
sed -n '1p' /etc/hostssed -n '2p' /etc/hosts
从管道读取数据:
echo "hello,world" | sed -n 'p'
该命令将输出 "hello,world"。
显示文件最后一行的内容:
sed -n '$p' /etc/hosts
显示以 "http" 开头的数据行:
sed -n '/^http/p' /etc/hosts
显示包含数字的数据行:
sed -n '/\d/p' /etc/hosts
显示以 "bash" 结尾的行并显示:
sed -n '/bash$/p' /etc/hosts
显示所有行的第 1 列到第 3 列:
sed -n '1~3p' /etc/hosts
多条 sed 指令可以通过分号分隔执行:
sed -n 'p; l' /etc/hosts
替换操作:
sed -n 's/old/new/g' /etc/hosts
该命令将将文件中的所有 "old" 替换为 "new"。
删除操作:
sed -i '/bash$/d' /etc/hosts
该命令将删除文件中所有以 "bash" 结尾的行。
将 sed 指令写入脚本文件后,可以使用 -f 选项执行:
sed -f scriptfile /etc/hosts
在实际操作中,建议先在备份文件上测试 sed 指令的效果。对于需要多次修改的文件,可以将 sed 指令写入脚本文件后使用 -f 选项执行。
通过以上命令,用户可以根据需要对文件进行增删改查操作。sed 提供了丰富的定位方式和操作指令,能够满足多种文件处理需求。
转载地址:http://oziy.baihongyu.com/