Linux之sed用法

sed命令基本用法(模式空间)

选项:
-n,--quiet,--silent
	使用安静模式。sed的一般用法中,所有来自STDIN的数据一般都会被打印到终端上,如果加上-n后,则只有经过sed特殊处理的那一行才会被列出来。
-e <script>,--expression=<script>
	指定sed动作,可以由多个-e指定多个动作。
-f <script-file>,--file=<script-file>
	直接将sed的动作写在一个文件内,-f filename则可以运行filename 内的sed动作;
-r,--regexp-extended
	sed支持扩展正则表达式(默认是基础正则表达式)。
-i 
	直接修改读取的文件内容,而不是输出到终端。
--help
	显示帮助
--version
	显示版本

动作说明:
//a   新增, a 的后面可以接字串,而这些字串会在新的一行出现
[root@master ~]# cat 123 
yexiaotian
Ni Hao
#在第二行之后添加
[root@master ~]# sed '2ahello world' 123  
yexiaotian
Ni Hao
hello world
#在匹配字符后添加
[root@master ~]# sed '/Ni Hao/ahello world' 123 
yexiaotian
Ni Hao
hello world

//i   插入, i 的后面可以接字串,而这些字串会在新的一行出现(目前的上一行)# 在第二行之前添加
[root@master ~]# sed '2ihello world' 123 
yexiaotian
hello world
Ni Hao
#在匹配字符前添加
[root@master ~]# sed '/Ni Hao/ihello world' 123 
yexiaotian
hello world
Ni Hao

//c   替换, c 的后面可以接字串,这些字串可以取代 n1,n2 之间的行
#替换第二行内容
[root@master ~]# sed '2chello world' 123 
yexiaotian
hello world
#替换匹配字符内容
[root@master ~]# sed '/Ni Hao/chello world' 123 
yexiaotian
hello world

//d   删除,因为是删除啊,所以 d 后面通常不接任何内容;
#删除第二行内容
[root@master ~]# sed '2d' 123 
yexiaotian
#删除匹配字符内容
[root@master ~]# sed '/Ni Hao/d' 123 
yexiaotian

//p   列印,亦即将某个选择的数据印出。通常 p 会与参数 sed -n 一起运行,打印到模式空间
# -n 安静模式 
[root@master ~]# sed -n '/yexiaotian/p' 123
yexiaotian
[root@master ~]# sed  '/yexiaotian/p' 123
yexiaotian
yexiaotian
Ni Hao

//y 替换全部 
[root@master ~]# sed 'y/y/Y/' 123 
Yexiaotian
Ni Hao

sed高级用法(多行模式空间)

  • h: 把模式空间中的内容覆盖至保持空间中
  • H:把模式空间中的内容追加至保持空间中
  • g: 从保持空间取出数据覆盖至模式空间
  • G:从保持空间取出内容追加至模式空间
//N 读取匹配到的行的下一行追加至模式空间
[root@master ~]# cat abc 
hello the world
hello minger
golang
python
c/c++
linux

[root@master ~]# sed 'N;D' abc 
linux
[root@master ~]# sed G abc 
hello the world

hello minger

golang

python

c/c++

linux



示例:
#sed命令在读取文件的第2行时将整行数据复制到保留空间,并将保留空间中原有的回车符覆盖
[root@master ~]# cat abc 
hello the world
hello minger
golang
python
c/c++
linux
[root@master ~]# sed '2d;5g' abc 
hello the world
golang
python

linux
# 使用的是大写字母G,是将保留空间中的数据追加第5行的后面,因此在c/c++后面添加了一行hello minger
[root@master ~]# sed '2h;5G' abc 
hello the world
hello minger
golang
python
c/c++
hello minger
linux

[root@master ~]# cat 1
1
2
3
11
22
33
111
222
333
[root@master ~]# sed '/1/{h;d}' 123
yexiaotian
Ni Hao
[root@master ~]# sed '/1/{h;d}' 1
2
3
22
33
222
333
[root@master ~]# sed '/1/{h;d};/2/{G}' 1
2
1
3
22
11
33
222
111
333

d 删除模式空间中的行
# 取出文件中的奇数行
[root@master ~]# sed 'n;d' abc 
hello the world
golang
c/c++

D 如果模式空间包含换行符,则删除直到第一个换行符的模式空间中的文本,并不会读取新的输入行,而使用合成的模式空间重新启动循环。如果模式空间不包含换行符,则会像发出d命令那样启动正常的新循环
#取文件最后一行
[root@master ~]# sed 'N;D' abc 
linux
x 把模式空间中的内容与保持空间中的内容进行互换
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值