第七节 流编辑器sed(stream editor)(7.2.1)

3,2 常用编辑命令
对文件内容的编辑命令 说明
d 删除匹配的行
p 打印匹配到的行
a文本内容 将文本内容添加到匹配行的下一行
i文本内容 将文本内容添加到匹配行的上一行
c文本内容 用文本内容替换匹配到的所有行
r 读入文件内容追加到匹配行的后面
R 读入文件一行的内容追加到匹配行的后面
w /dir/filename 将匹配行的内容另存到/dir/filename中
s /pattern/replacement/flag 根据正则表达式进行匹配,将匹配到的内容替换为replacment, flag可以指定 g(表示全局替换,默认只替换每行第一个), num1(表示)

示例:

生成测试文件

shell 复制代码
sed -e '\#adm#,$#:#@@@#g' testfile

a)删除行

shell 复制代码
sed '1d' testfile
sed '$d' testfile
sed '/root/d' testfile
sed '/root/! d' testfile

b)显示行

shell 复制代码
sed -n '1p' testfile
sed -n '$p' testfile
sed -n '/root/p' testfile
sed -n '/root/! p' testfile

c)添加,插入,替换行

shell 复制代码
sed '1ahello world' testfile 
sed '$ahello world' testfile
sed '/adm/ahello world' testfile
sed '/adm/ihello world' testfile
sed '/adm/! ihel1o\nworld' testfile

d)整合文件

shell 复制代码
vim numfile1
1
2
6
vim numfile2
2
3
4
sed '1rnumfile2' numfile1
sed '1Rnumfile2' numfile1

e)保存处理结果

shell 复制代码
sed '/root/w file' testfile
cat file
root: x: 0:0: root:/root:/bin/bash

f)字符替换

shell 复制代码
sed 's/:/##/' testfile
sed 's/:/##/2' testfile 
sed 's/:/##/g' testfile 
sed 's/^./##/g' testfile
sed 's/^\< [a-z]*[a-Z \>//' testfile 
sed 's/^\(...\)\(t\)/\2/g' testfile #元素向后引用
t: x: 0:0: root:/root:/bi n/bash
相关推荐
HarrySunCn11 小时前
如何使用VSCode开发Arduino项目
ide·vscode·单片机·编辑器
bulucc17 小时前
vim 快捷操作
linux·编辑器·vim
超超~~1 天前
Notepad(文本编辑器)v3.6.30绿色官方版
编辑器·notepad++
shhpeng1 天前
Visual Studio Code 下 go 开发环境搭建
ide·vscode·编辑器
AlbertS1 天前
Shell脚本中set -e和set -o pipefail的作用
shell·pipefail·trap·脚本错误·控制流程
为什么要内卷,摆烂不香吗1 天前
sed 流编辑器练习自用
linux·运维·编辑器
承接电子控制相关项目2 天前
安装VSCODE发现 右击选项中无VSCODE 打开选项,处理方法汇总
ide·vscode·编辑器
我是菜鸟0713号2 天前
VSCode配置Qt6开发教程
ide·vscode·编辑器
阿海5742 天前
安装php7.4.33的shell脚本
php·shell
lanhuazui102 天前
VScode中函数和变量跳转定义配置文件设置
vscode·编辑器