Linux sed编辑器

作者: SnailTyan | 来源:发表于2017-01-11 22:07 被阅读43次

    文章作者:Tyan
    博客:noahsnail.com | CSDN | 简书

    1. sed编辑器

    sed编辑器中是Linux世界中最广泛使用的两个命令行编辑器之一。sed编辑器被称作流编辑器(stream editor),流编辑器在编辑器处理数据之前基于预先提供的一组规则来编辑数据流。sed编辑器可以根据命令来处理数据流中的数据。sed编辑器会执行以下操作:

    1. 一次从输入中读取一行数据。
    2. 根据所提供的编辑器命令匹配数据。
    3. 按照命令修改流中的数据。
    4. 将新的数据输出到STDOUT。

    在流编辑器将所有命令和一行数据匹配完毕后,它会读取下一行数据重复这个过程。

    2. 命令形式

    sed命令的格式如下:

    sed options script file
    

    3. Demo

    • 基本处理
    $ echo "This is a test" | sed 's/test/big test/'
    This is a big test
    

    上面的例子中使用了s命令,s命令会用斜线中的第二个文本来替换第一个文本。处理文件如下:

    # test文件内容
    
    $ cat test
    This is a test.
    This is a test.
    This is a test.
    This is a test.
    This is a test.
    
    
    # sed处理
    $ sed 's/test/demo/' test
    This is a demo.
    This is a demo.
    This is a demo.
    This is a demo.
    This is a demo.
    
    # test文件内容
    $ cat test
    This is a test.
    This is a test.
    This is a test.
    This is a test.
    This is a test.
    

    注:sed编辑器不会修改文本文件的数据,它只会将处理后的数据发送到STDOUT。

    • 执行多个命令

    -e选项可以执行多个命令,多个命令用;隔开。

    $ sed -e 's/a/an/; s/test/egg/' test
    This is an egg.
    This is an egg.
    This is an egg.
    This is an egg.
    This is an egg.
    
    • 从文件中读取命令

    -f选项可以让sed执行文件中的命令。

    $ cat script.sed
    s/a/an/
    s/test/egg/
    
    $ sed -f script.sed test
    This is an egg.
    This is an egg.
    This is an egg.
    This is an egg.
    This is an egg.
    

    参考文献

    1. Linux命令行与shell脚本编程

    相关文章

      网友评论

        本文标题:Linux sed编辑器

        本文链接:https://www.haomeiwen.com/subject/nlarbttx.html