linux 命令之sed

sed:用于过滤和转换文件的流编辑器

执行方式: sed [options] 'command' [filename]   

                   sed [options] '/pattern/ command'

                   sed [options] 'n,m command'  (n,m为行号)

command(命令):

s/re/string/   : 替换  使用字符串string替换正则表达式re的内容 (只替换第一个)

#echo hello gino hello wrold | sed 's/\<hello\>/Hello/'
Hello gino hello wrold

g :行内全部替换

# echo hello gino hello wrold | sed 's/\<hello\>/Hello/g'
Hello gino Hello wrold
匹配样式的行进行替换示例 :
# cat sample_one 
one 	1
two	1
three	1
one	1
two	1
two	1
three	1

# sed '/two/ s/1/2/' sample_one 
one 	1
two	2
three	1
one	1
two	2
two	2
three	1


d : 删除行

# sed '/two/ d' sample_one 
one 	1
three	1
one	1
three	1
# sed '/two/ !d' sample_one  #删除匹配以外的行 
two	1
two	1
two	1
# sed '1,5 d' sample_one    #删除第1到第5行
two	1
three	1


i\ :插入文本(行前)

# sed '5 i\hello gino' sample_one 
one 	1
two	1
three	1
one	1
hello gino
two	1
two	1
three	1

a\ :追加文本(行后)

# sed '5 a\hello gino' sample_one 
one 	1
two	1
three	1
one	1
two	1
hello gino
two	1
three	1


c\ : 替换文本(本行)

# sed '5 c\hello gino' sample_one 
one 	1
two	1
three	1
one	1
hello gino
two	1
three	1


p : 打印

# sed '5 p' sample_one one 	1
two	1
three	1
one	1
two	1
two	1
two	1   #打印出来的一行
three	1


w : 写入到文件结尾

# sed -e '/two/ s/1/2/' -e '/three/ s/1/3/' -e '1,3 w sample_two' sample_one   
one		1
two		2
three		3
one		1
two		2
two		2
three		3
# cat sample_two 
one		1
two		2
three		3


q : 提前退出

# sed '3q' sample_one #处理到第三行就退出sed命令
one		1
two		1
three		1





options(选项):

-f : 从文件中读取替换规则

# cat replace_list /two/ s/1/2/
/three/ s/1/3/
# sed -f replace_list sample_one 
one 	1
two	2
three	3
one	1
two	2
two	2
three	3

-n : 禁止显示

# sed -n '/two/ d' sample_one   #不显示结果



-i  :对文件进行操作(不加此选项 不改变文件的内容,只改变显示的结果而已)

# cat sample_one 
two	1
#sed -i 'p' sample_one  
# cat sample_one   #源文件被改变了
two	1
two	1


-e : 执行多个sed

# sed -e '/two/ s/1/2/' -e '/three/ s/1/3/' sample_one 
one		1
two		2
three		3
one		1
two		2
two		2
three		3

ubuntu还支持另外一种 执行多个sed 的语法(其他linux系统没尝试)

 

# sed '/two/ s/1/2/;/three/ s/1/3/' sample_one 
one		1
two		2
three		3
one		1
two		2
two		2
three		3



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值