功能强大的sed用法

sed是一个“非交互式的”面向字符流的编辑器。可以对文本文件进行增、删、改、查等操作,支持按行、按字段、按正则匹配文本内容,非常灵活和方便,特别适合于大文件的编辑。
sed在处理文本时会逐行读取文件内容,读到匹配的行就根据指令做操作,不匹配就跳过。


1.sed命令的语法格式

命令格式: sed [option] ‘sed command’ filename

【option】
-n :只打印模式匹配的行
-e :直接在命令行模式上进行sed动作编辑,此为默认选项
-f :将sed的动作写在一个文件内,用–f filename 执行filename内的sed动作
-r :支持扩展表达式
-i :直接修改文件内容
【sed command】
a :append,追加新行
c :cover,覆盖指定的行
d :delete,删除区间行
i :insert,在指定行前面插入一行,同a相反
p :print,和-n配合
s :substitute,取代

2、例子

追加a(和i有差别,a是在某行之后插入)


 sed '2anewline' myfile.txt   # 第二行后追加字符串“newline”

 sed '2,4anewline' myfile.txt  # 第24行后追加字符串“newline”,每一行都会追加

 sed '/ccc/anewline' myfile.txt   # 在包含ccc的每一行后追加字符串“newline”

 sed '2,4!anewline' myfile.txt   # 除了第24行以外的行后面后追加字符“newline”,每一行都会追加

 sed '/ccc/,$anewline' myfile.txt   # 在包含ccc的行,到最后一行,每一行之后追加字符串“newline”

 sed '/ccc/,+1anewline' myfile.txt   # 在包含ccc的行,以及之后的1行,每一行之后追加字符串“newline”

插入i(和a有差别,i是在某行之前插入)

sed '2inewline' mytestfile.txt   #第二行之前追加字符串“newline”

sed '2,4inewline' mytestfile.txt  #第24行之前追加字符串“newline”,每一行都会追加

覆盖

 sed '2cnewline' myfile.txt     # 第二行删除后,替换成newline

 sed '2,4cnewline' myfile.txt   # 第24行删除后,替换成newline(注意只添加了一行newline字符串)

删除

sed '2d' mytestfile.txt  #删除第2行

sed '2,4d' mytestfile.txt  #删除第2~4行

sed '2,$d' mytestfile.txt  #删除第2~最后1

替换

sed 's/fff/good/g' mytestfile.txt   #将每一行中,所有匹配到字符串“fff”的地方,都替换成good

sed 's/f/good/3' mytestfile.txt    #将每一行中,第三个匹配到字符串“f”的地方,替换成good

读写文件

sed '$r mytestfile2.txt' mytestfile.txt  #将文件mytestfile2.txt的内容,写入mytestfile.txt的末尾

sed '3r mytestfile2.txt' mytestfile.txt  #将文件mytestfile2.txt的内容,写入mytestfile.txt的3行

sed 'w mytestfile2.txt' mytestfile.txt  #将文件mytestfile.txt写入mytestfile2.txt

sed '2w mytestfile2.txt' mytestfile.txt  #将文件mytestfile.txt的第2行,写入mytestfile2.txt

打印

sed -n '2p' mytestfile.txt   #打印第2行,-n是用来不输出原本文件

sed -n '2,4p' mytestfile.txt  #打印第2~4行,-n是用来不输出原本文件

sed -n '/f/p' mytestfile.txt  #将包含f的行都打印出来,-n是用来不输出原本文件

以上命令只会在终端显示效果,不会修改文件;想实现修改需要加参数-i

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值