1 2 3 4

sed流编辑器

sed流编辑器

strem editor流编辑器
sed编辑器是一行一行的处理文件内容的

正在处理的内容存放在模式空间(缓冲区)内,处理完成后按照选项的规定进行输出或文件的修改
接着处理下一行,这样不断重复,直到文件末尾,文件内容并没有改变,除非你使用重定向存储输出
sed主要用来自动编辑一个或多个文件,简化对文件的反复操作

sed是支持正则表达式的,如果要使用扩展正则加参数,-r

sed的执行过程

  1. 读取一行数据
  2. 根据我们提供的规则来匹配相关的数据
  3. 安装命令修改数据流中的数据,比如替换
  4. 将结果进行输出
  5. 重复上面4步

语法格式

语法

sed [option] '[commands]' filename

选项参数

  • -a 在当前行下面插入文件
  • -n 读取下一个输入行,用下一个命令处理新的行而不是用第一个命令
  • -e 执行多个sed指令
  • -f 运行脚本
  • -i 编辑文件内容
  • -i.bak 编辑的同时创造.bak的备份
  • -r 使用扩展的正则表达式

命令

  • i 在当前行上面插入文件
  • c 把选定的行改为新的指定的文本
  • p 打印
  • d 删除
  • r 文件
  • w 另存
  • s 查找
  • y 替换

查找替换

查找apple并将其替换为dog

[root@localhost ~]# echo 'this is apple' | sed 's/apple/dog/'
this is dog

查找a.txt文件中的apple并将其替换为dog

[root@localhost ~]# echo 'this is apple' > a.txt
[root@localhost ~]# sed 's/apple/dog/' a.txt 
this is dog

将passwd中的root替换为xue

只替换第一个匹配到的字符

[root@localhost ~]# sed 's/root/xue/' /etc/passwd | more

全面替换标记g

[root@localhost ~]# sed 's/root/xue/g' /etc/passwd | more

将passwd中的/sbin/nologin改为/bin/bash

[root@localhost ~]# sed 's/\/sbin\/nologin/\/bin\/bash/g' /etc/passwd

[root@localhost ~]# sed 's#/sbin/nologin#/bin/bash#g' /etc/passwd

按行查找替换

用数字表示范围
$表示行尾
用文本模式配置来过滤

单行替换,将第2行中所有的bin替换为xue

[root@localhost ~]# sed '2s/bin/xue/g' /etc/passwd

多行替换,将第3行到行尾中bin替换为xue

[root@localhost ~]# sed '3,$s/bin/xue/g' /etc/passwd

删除行

删除第2行到第4行的内容

[root@localhost ~]# sed '2,4d' /etc/hosts

删除包括127.0.0.1的行

[root@localhost ~]# sed '/127.0.0.1/d' /etc/hosts

添加行

命令i(insert),在当前行前面插入一行
命令a(append),在当前行后面添加一行

[root@localhost ~]# echo "hello" | sed 'i\world'
world
hello
[root@localhost ~]# echo "hello" | sed 'a\world'
hello
world
[root@localhost ~]# 

在最后一行添加192.168.1.65 xue65.cn

[root@localhost ~]# sed '$a\192.168.1.65 xue65.cn' /etc/hosts

在第2行后面添加一行,192.168.1.63 xue63.cn

[root@localhost ~]# sed '2a\192.168.1.63 xue63.cn' /etc/hosts

在首行添加一行,192.168.1.1 xue1.cn

[root@localhost ~]# sed '1i\192.168.1.1 xue1.cn' /etc/hosts

在第一行后和末尾分别追加一行,hello

[root@localhost ~]# sed '1,$a\hello' /etc/hosts

修改行

c(change)

将第2行修改为192.168.1.53 xue53.cn

[root@localhost ~]# sed '2c\192.168.1.53 xue53.cn' /etc/hosts

将包含127.0.0.1的行改为192.168.1.54

[root@localhost ~]# sed '/127.0.0.1/c\192.168.1.54' /etc/hosts

打印,直接输出文件中的内容

输出第4行内容

[root@VM_0_7_centos ~]# sed -n '4p' /etc/hosts

输出全部内容

[root@VM_0_7_centos ~]# sed -n '1,$p' /etc/hosts

另存为

将修改或过滤出来的内容保存到另一个文件中

[root@VM_0_7_centos ~]# sed -n '/root/w 1.txt' /etc/passwd
[root@VM_0_7_centos ~]# cat 1.txt 
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin

对源文件进行修改 -i

[root@localhost ~]# sed -i 's/root/xue/g' 1.txt 

修改配置文件,关闭网络服务

[root@localhost network-scripts]# sed -i 's/ONBOOT=yes/ONBOOT=no/' ifcfg-ens33 

posted @ 2020-01-07 20:05  多走多看  阅读(139)  评论(0编辑  收藏  举报