zoukankan      html  css  js  c++  java
  • sed语法

    Sed 命令行

    以下是我们可以指定单引号在命令行sed命令的格式如下:

    sed [-n] [-e] 'command(s)' files 
    

    例子

    考虑一下我们有一个文本文件books.txt待处理,它有以下内容:

    1) A Storm of Swords, George R. R. Martin, 1216 
    2) The Two Towers, J. R. R. Tolkien, 352 
    3) The Alchemist, Paulo Coelho, 197 
    4) The Fellowship of the Ring, J. R. R. Tolkien, 432 
    5) The Pilgrimage, Paulo Coelho, 288 
    6) A Game of Thrones, George R. R. Martin, 864
    

    首先,让我们不带任何命令使用sed文件的完整显示内容如下:

    [jerry]$ sed '' books.txt
    

    执行上面的代码,会得到如下结果:

    1) A Storm of Swords, George R. R. Martin, 1216
    2) The Two Towers, J. R. R. Tolkien, 352
    3) The Alchemist, Paulo Coelho, 197
    4) The Fellowship of the Ring, J. R. R. Tolkien, 432
    5) The Pilgrimage, Paulo Coelho, 288
    6) A Game of Thrones, George R. R. Martin, 864
    

    现在,我们从上述文件中显示将看到sed的delete命令删除某些行。让我们删除了第一,第二和第五行。在这里,要删除给定的三行,我们已经指定了三个单独的命令带有-e选项。

    [jerry]$ sed -e '1d' -e '2d' -e '5d' books.txt 
    

    执行上面的代码,会得到如下结果:

    3) The Alchemist, Paulo Coelho, 197 
    4) The Fellowship of the Ring, J. R. R. Tolkien, 432 
    6) A Game of Thrones, George R. R. Martin, 864 
    

    sed脚本文件

    下面是第二种形式,我们可以提供一个sed脚本文件sed命令:

    sed [-n] -f scriptfile files
    

    首先,创建一个包含在一个单独的行的文本commands.txt文件,每次一行为每个sed命令,如下图所示:

    1d 
    2d 
    5d 
    

    现在,我们可以指示sed从文本文件中读取指令和执行操作。这里,我们实现相同的结果,如图在上述的例子。

    [jerry]$ sed -f commands.txt books.txt
    

    执行上面的代码,会得到如下结果:

    3) The Alchemist, Paulo Coelho, 197 
    4) The Fellowship of the Ring, J. R. R. Tolkien, 432 
    6) A Game of Thrones,George R. R. Martin, 864 
    

    sed标准选项

    sed支持可从命令行提供下列标准选择。

     -n 选项

    这是模式缓冲区的缺省打印选项。 GNU sed解释器提供--quiet,--silent选项作为 -n选项的替代。

    例如,下面 sed 命令不显示任何输出:

    [jerry]$ sed -n '' quote.txt 
    

    -e 选项

    -e选项的编辑选项。通过使用此选项,可以指定多个命令。例如,下面 sed 命令打印每行两次:

    [jerry]$ sed -e '' -e 'p' quote.txt
    

    执行上面的代码,会得到如下结果:

    There is only one thing that makes a dream impossible to achieve: the fear of failure. 
    There is only one thing that makes a dream impossible to achieve: the fear of failure. 
     - Paulo Coelho, The Alchemist 
     - Paulo Coelho, The Alchemist
    

    -f 选项

    -f选项是用来提供包含sed命令的文件。例如,我们可以按如下方法通过文件指定一个打印命令:

    [jerry]$ echo "p" > commands.txt 
    [jerry]$ sed -n -f commands quote.txt
    

    执行上面的代码,会得到如下结果:

    There is only one thing that makes a dream impossible to achieve: the fear of failure. 
     - Paulo Coelho, The Alchemist


  • 相关阅读:
    @当你输入一个网址的时候,实际会发生什么?
    @Java魔法类——unsafer应用解析
    !@面试官:说说双亲委派模型?
    @JAVA字符串格式化
    @double精度比float低吗?
    @java类中资源加载顺序
    !@阿里资深架构师浅谈一个Java类的生命周期
    @String对象的那些事,几行代码就解释得清清楚楚
    @final、finally、finalize有什么区别?
    @35个Java代码优化的细节,你知道几个?
  • 原文地址:https://www.cnblogs.com/duanlinxiao/p/10778571.html
Copyright © 2011-2022 走看看