sed 字符替换命令

sed 命令

sed 是一种几乎包括在所有 UNIX 平台(包括 Linux)的轻量级流编辑器。sed 主要是用来将数据进行选取、替换、删除、新增的命令。

格式:

sed [选项] ‘[动作]’ 文件名

选项:

  • -n:一般 sed 命令会把所有数据都输出到屏幕,如果加入此选项则只会把经过 sed 命令处理的行输出到屏幕。
  • -e:允许对输入的数据应用多条 sed 命令编辑。
  • -i:用 sed 的修改结果直接修改读取数据的文件,而不是由屏幕输出。

动作:

  • a:追加,在当前行后添加一行或多行。
  • c:行替换,用 c 后面的字符串替换原数据行。
  • i:插入,在当前行前插入一行或多行。
  • d:删除,删除指定的行。
  • p:打印,输出指定的行。
  • s:字符替换,用一个字符串替换另外一个字符串。格式为“行范围s/旧字串/新字串/g”(和 vim 中的替换格式类似)

行数据操作

[root@localhost ~]# sed '2p' student.txt #没有 -n 选项输出所有内容,而且会重复,'2p' 代表打印第二行
ID  Name    Gender  Mark
1   stu1    F       95
1   stu1    F       95
2   stu2    F       85
3   stu3    F       75
[root@localhost ~]# sed -n '2p' student.txt #有-n 选项则打印指定行
1   stu1    F   95
[root@localhost ~]# sed '2d' student.txt #'2d' 代表删除第二行内容,不修改原文件
ID  Name    Gender  Mark
2   stu2    F       85
3   stu3    F       75
[root@localhost ~]# sed '2,4d' student.txt #'2,4d' 代表删除第二行到第四行所有内容,不修改原文件
ID  Name    Gender  Mark
[root@localhost ~]# sed '2a hello' student.txt #在第二行后追加一行内容为 hello,不修改原文件
ID  Name    Gender  Mark
1   stu1    F       95
hello
2   stu2    F       85
3   stu3    F       75

[root@localhost ~]# sed '2i hello' student.txt #在第二行前插入一行内容为 hello,不修改原文件
ID  Name    Gender  Mark
hello
1   stu1    F       95
2   stu2    F       85
3   stu3    F       75
[root@localhost ~]# sed '4c test' student.txt #替换第四行内容为 test,不修改原文件
ID  Name    Gender  Mark
1   stu1    F       95
2   stu2    F       85
test

字符串替换

sed ‘s/旧字串/新字串/g’ 文件名 # g 代表替换所有字符串

[root@localhost ~]# sed '4s/75/100/g' student.txt #替换第四行的 75 为 100,不修改原文件
ID  Name    Gender  Mark
1   stu1    F       95
2   stu2    F       85
3   stu3    F       100

[root@localhost ~]# sed -i '4s/75/100/' student.txt # -i 选项会修改原文件内容,但不再打印到屏幕
[root@localhost ~]# cat student.txt #原文件内容已更改 
ID  Name    Gender  Mark
1   stu1    F       95
2   stu2    F       85
3   stu3    F       100
[root@localhost ~]# sed -e 's/stu1//g;s/stu3//g' student.txt #-e 执行多条语句,用分号隔开,将 stu1 和 stu3 内容替换为空,替换原文件用 -ie,-ei 会报错
ID  Name    Gender  Mark
1           F       95
2   stu2    F       85
3           F       100
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值