shell-sed

一、基础语法

sed [-nefr] [操作]
-n 一般情况下,如果不加-n,所有的数据都会被打印在屏幕上,但是加上-n之后,只有经过sed处理的那一行才会被打印到屏幕上
-i 一般情况下,如果不加-i,只会对输出的内容做更改,并不会对文件内容作更改,如果想要更改文件内容,则需要加-i参数 -n与-i一般不要在一起使用

[操作]说明:[n1[,n2]]function
n1 n2指代的是行数 最小为1,不支持0
如果是n1,n2 是指从第n1行到第n2行
如果是n 一个数字,则指代第n行
不存在n1,function 或者,n2function这样的情况,否则会报错,实践如下:

[yiifung@localhost ~]$ sed -n 1,2p  test1
0
1
[yiifung@localhost ~]$ sed -n 1,p  test1
sed: -e expression #1, char 3: unexpected `,'
[yiifung@localhost ~]$ sed -n ,2p  test1
sed: -e expression #1, char 1: unknown command: `,'
[yiifung@localhost ~]$ sed -n 2p  test1
1
[yiifung@localhost ~]$ 

function 有如下类型

a 新增,新增一行,a的后面可以接字符,而这些字符会出现在新的一行(目前的下一行)

[yiifung@localhost ~]$ cat test1
0
1
2
3
4

[yiifung@localhost ~]$ sed -i 2ahello  test1
[yiifung@localhost ~]$ cat test1
0
1
hello
2
3
4

[yiifung@localhost ~]$ 

i 插入,插入一行,i的后面可以接字符,而这些字符会出现在新的一行(目前的上一行)

yiifung@localhost ~]$ cat test1
0
1
hello
2
3
4

[yiifung@localhost ~]$ sed -i 2iaaaa  test1
[yiifung@localhost ~]$ cat test1
0
aaaa
1
hello
2
3
4

d 删除,因为是删除,所以d后面不接任何东西

yiifung@localhost ~]$ cat test1
0
aaaa
1
hello
2
3
4

[yiifung@localhost ~]$ sed -i 2d  test1
[yiifung@localhost ~]$ cat test1
0
1
hello
2
3
4

c 替换,c的后面可以接字符,这些字符可以替换n1到n2之间的行

[yiifung@localhost ~]$ cat test1
0
1
hello
2
3
4

[yiifung@localhost ~]$ sed -i '1,3chello world'  test1
[yiifung@localhost ~]$ cat test1
hello world
2
3
4

p 打印,将某个选择的数据打印出来,通常p会与参数sed -n 一起使用
sed -n 1,4p 文件名
sed -n ‘1,4p’ 文件名

[yiifung@localhost ~]$ sed -n '1,3p'  test1
hello world
hello world
2

s 替换,可以直接替换,通常这个s的选项可以搭配正则表达式,例如: ‘1,2s/old/new/g’ 或者 1,2s/old/new/g 带不带引号都可以
或者 ‘1,2s/old/new/’
‘1,2s/old/new/g’ 与 ‘1,2s/old/new/’ 做对比,两者的区别是最后带不带g,如果带g,则会替换当前行出现的所有匹配上的值;如果不带g,则只会替换当前行出现的第一个值,不会替换该行其他值

[yiifung@localhost ~]$ cat test1
hello world
hello world
2  2  2  2  2
2 2 2
3 2 2 
3  2 2 2
4

[yiifung@localhost ~]$ sed -i '3,6s/2/huster/'  test1
[yiifung@localhost ~]$ cat test1
hello world
hello world
huster  2  2  2  2
huster 2 2
3 huster 2 
3  huster 2 2
4

[yiifung@localhost ~]$ sed -i '3,6s/2/huster/g'  test1
[yiifung@localhost ~]$ cat test1
hello world
hello world
huster  huster  huster  huster  huster
huster huster huster
3 huster huster 
3  huster huster huster
4

[yiifung@localhost ~]$ 

二、注意事项

1、cat test | sed -n 1ahh 这种方式不会真正更改文件
2、-i参数才会更改生效

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值