sed常用操作命令

sed: stream editor , 流/行 编辑器 ;

sed 命令详解:

sed [OPTIONS]...  {script-only-if-no-other-script}  [input-file]...

OPTIONS:

        -n, --quiet, --silent , suppress automatic printing of pattern space /禁止打印pattern space 内容

         -e script  ,--expression=script ,add the script to the commands to be executed ,支持多级编辑

          -f script-file, --file=script-file ,  add the contents of script-file to the commands to be executed,将命令汇总至script-file 方便执行

          -r, --regexp-extended ,use extended regular expressions in the script. 使用扩展正则表达式

           -i[SUFFIX], --in-place[=SUFFIX] : 直接编辑原文件


 script-only-if-no-other-script  :包括地址限定 和  编辑命令;

  地址限定:

        (1) #,# , 指定单行; $ : 最后一行

        (2) #1,+#, 指定多个单行

         (3)#,/pattern/         ## 匹配从第# 开始到第一次匹配到/pattern1/之间的行

         (4)/pattern1/, /pattern1/

        (5)first~step ,Match every step'th line starting with line first.

                eg: the address 2~5 will match every fifth line, starting with the second . 从第2行开始,每隔5行;


常见的编辑命令有:

         d  Delete pattern space. 删除pattern space 中的内容;

         p Print the current pattern space. .打印pattern space中的内容

        a \text  : append , 在匹配到的pattern行的下方追加一行

        i \text  :insert , 在匹配到的pattern行的上方插入一行

        r filename : Append text read from filename.  将filename 追加读入当前匹配到pattern的行的下方

        c \text ,Replace the selected lines with text ,替换匹配到pattern行为text ;

        w filename, Write the current pattern space to filename. 将匹配到pattern内容的行保存至filename中;

        s/regexp/replacement/opts : 将匹配到regexp 的内容替换为replacement

               其中,常用opts 有:

                        g: 全局替换

                        p: 显示替换成功的行

                        w  /PATH/FILENAME :  将替换成功的结果保存至指定文件中

 示例:

>>>sed -n '1,+4p' /etc/passwd           

root:x:0:0:root:/root:/bin/bash

bin:x:1:1:bin:/bin:/sbin/nologin

daemon:x:2:2:daemon:/sbin:/sbin/nologin

adm:x:3:4:adm:/var/adm:/sbin/nologin

lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

>>>sed '1,/^tome/ d' /etc/passwd

tom:x:4012:4012::/home/tom:/bin/bash

>>>sed -n -e '/^root/a \Superman' -e '/^root/i \superman' /etc/passwd


##删除/etc/init.d/functions 文件中所有以空白字符开头的行的行首的所有空白字符;

>>sed 's@^[[:space:]]\+@@g' /etc/init.d/functions


##删除/etc/fstab文件中所有以#开头的行的行首的# 号及#后面的所有空白字符;

>>>sed 's@^#\+[[:space:]]*@@g' /etc/fstab

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.创建文件夹 !/bin/sh mkdir -m 777 "%%1" 2.创建文件 !/bin/sh touch...
    BigJeffWang阅读 13,447评论 3 53
  • “文本三剑客”中,grep是文本过滤器,而sed是基于行的文本流编辑器。sed是将文件中的文本逐行读取到内存中进行...
    学渣角鹿白阅读 3,899评论 0 2
  • linux资料总章2.1 1.0写的不好抱歉 但是2.0已经改了很多 但是错误还是无法避免 以后资料会慢慢更新 大...
    数据革命阅读 14,186评论 2 33
  • awk命令的基本使用 [root@shellscript ~]# head -n 3 /etc/passwd | ...
    古寒飞阅读 4,678评论 0 2
  • 【蹦蹦跳跳皮皮猴】20171229学习力践行71 今天爸妈很给力,不看电视,定时吃饭定时睡觉,一直陪着小家伙看书看...
    汤伊森阅读 806评论 0 0