sed

sed 是流编辑器

命令格式

sed [options] 'command' file(s)
sed [options] -f scriptfile file(s)

选项

-e<script>或--expression=<script>:以选项中的指定的script来处理输入的文本文件;
-f<script文件>或--file=<script文件>:以选项中指定的script文件来处理输入的文本文件;
-h或--help:显示帮助;
-n或--quiet或——silent:仅显示script处理后的结果



正则
^ 匹配行开始,如:/^sed/匹配所有以sed开头的行。
$ 匹配行结束,如:/sed$/匹配所有以sed结尾的行。
. 匹配一个非换行符的任意字符,如:/s.d/匹配s后接一个任意字符,最后是d。
* 匹配0个或多个字符,如:/*sed/匹配所有模板是一个或多个空格后紧跟sed的行。
[] 匹配一个指定范围内的字符,如/[ss]ed/匹配sed和Sed。  
[^] 匹配一个不在指定范围内的字符,如:/[^A-RT-Z]ed/匹配不包含A-R和T-Z的一个字母开头,紧跟ed的行。
(..) 匹配子串,保存匹配的字符,如s/(love)able/1rs,loveable被替换成lovers。
& 保存搜索字符用来替换其他字符,如s/love/**&**/,love这成**love**。
< 匹配单词的开始,如:/<love/匹配包含以love开头的单词的行。
> 匹配单词的结束,如/love>/匹配包含以love结尾的单词的行。
x{m} 重复字符x,m次,如:/0{5}/匹配包含5个0的行。
x{m,} 重复字符x,至少m次,如:/0{5,}/匹配至少有5个0的行。
x{m,n} 重复字符x,至少m次,不多于n次,如:/0{5,10}/匹配5~10个0的行。


sed命令 -n选项和p命令一起使用表示只打印那些发生替换的行:

 替换

  简单替换

    sed 's/book/books/' file
    sed '1,10y/abcde/ABCDE/' file 不能运用于正则

  复杂替换

     引用,sed表达式可以使用单引号来引用,但是如果表达式内部包含变量字符串,就需要使用双引号。

    test=hello
    echo hello WORLD | sed "s/$test/HELLO"
    HELLO WORLD

    匹配符
     w+ 匹配每一个单词,使用 [&] 替换它
      echo this is a test line | sed 's/w+/[&]/g'
      [this] [is] [a] [test] [line]


    具体匹配项 num 具体某项
      echo this is digit 7 in a number | sed 's/digit ([0-9])/1/'
      this is 7 in a number

筛选

  奇偶行 

   sed -n 'p;n' test.txt  #奇数行  
    sed -n 'n;p' test.txt  #偶数行

   范围1

    sed -n '/a/,/f/p' a

  范围2

    sed -n '5,/^f/p' a

  范围3

     sed -n '5,10p' a

  范围4

    sed -n '/[a*]/,10p' a

  范围5

    sed -n '1,10!p' a

删除

  删除空白行:

   sed '/^$/d' file

  删除文件的第2行:

  sed '2d' file

  删除文件的第2行到末尾所有行:

  sed '2,$d' file

  删除文件最后一行:

  sed '$d' file

  删除文件中所有开头是test的行:

  sed '/^test/d' file

新增

  从文件读入:r命令

  file里的内容被读进来,显示在与test匹配的行后面,如果匹配多行,则file的内容将显示在所有匹配行的下面:

  sed '/test/r file' filename

  写入文件:w命令  

  在example中所有包含test的行都被写入file里:

  sed -n '/test/w file' example

  追加(行下):a命令

  将 this is a test line 追加到 以test 开头的行后面:

  sed '/^test/athis is a test line' file

  在 test.conf 文件第2行之后插入 this is a test line:

  sed -i '2athis is a test line' test.conf

  插入(行上):i命令

  将 this is a test line 追加到以test开头的行前面:

  sed '/^test/ithis is a test line' file

  在test.conf文件第5行之前插入this is a test line:

  sed -i '5ithis is a test line' test.conf
原文地址:https://www.cnblogs.com/zhco/p/9535038.html