【问题标题】:search for exact pattern using sed and print in new line使用 sed 搜索精确模式并在新行中打印
【发布时间】:2014-11-01 19:14:17
【问题描述】:

我有一个大文件,其中包含类似

的数据
cd24511   |cd25512|cd24541|cd11554            0| cd24512      |cd24542|cd24531            0| cd24513      |cd24543        0| cd27531      |cd27531|cd27541            2740| cd27521   |cd27541            2261|

我想通过以下方式使用 sed 对其进行格式化。

cd24511  |cd25512|cd24541|cd11554  0|

cd24512  |cd24542|cd24531          0|

cd24513  |cd24543                  0|

cd27531  |cd27531|cd27541          2740|

cd27521  |cd27541                  2261|

如果我使用 sed 搜索数字模式,它会列出所有数字,如下所示

245112551224541115540245122454224531024513245430

【问题讨论】:

    标签: regex linux bash sed


    【解决方案1】:

    这是一种方法:

    $ sed -r 's/\s+[0-9]+\s*\|/&\n/g' file | column -t 
    cd24511  |cd25512|cd24541|cd11554  0|
    cd24512  |cd24542|cd24531          0|
    cd24513  |cd24543                  0|
    cd27531  |cd27531|cd27541          2740|
    cd27521  |cd27541                  2261|
    

    不确定你是否真的想要空行,但你可以这样做:

    $ sed -r 's/\s+[0-9]+\s*\|/&\n/g' file | column -t | sed 's/$/\n/'      
    cd24511  |cd25512|cd24541|cd11554  0|
    
    cd24512  |cd24542|cd24531          0|
    
    cd24513  |cd24543                  0|
    
    cd27531  |cd27531|cd27541          2740|
    
    cd27521  |cd27541                  2261|
    

    说明:

    分解第一个sed 脚本:

    s        # substitution command 
    
    /        # start of regular expression match 
    
    \s+      # one or more whitespace characters
    [0-9]+   # one or more digits
    \s*      # zero or more whitespace characters
    \|       # literal | character 
    /        # end of regular expression match, start of replacement
    
    &\n      # & contains the match, add the newline character 
    
    /        # end of replacement, start of flags
    
    g        # global flag
    

    column -t 命令为我们处理表格布局,双倍行距将每行的结尾$ 替换为换行符\n

    【讨论】:

      【解决方案2】:

      这是awk 解决方案。

      awk '{for (i=1;i<=NF;i++) if ($i~/^[0-9]+\|/) $i=$i"\n"}1' file | column -t
      cd24511  |cd25512|cd24541|cd11554  0|
      cd24512  |cd24542|cd24531          0|
      cd24513  |cd24543                  0|
      cd27531  |cd27531|cd27541          2740|
      cd27521  |cd27541                  2261|
      

      它测试所有字段,如果它只包含数字和|,则添加换行符。

      【讨论】:

        猜你喜欢
        • 2013-03-21
        • 2016-07-13
        • 1970-01-01
        • 2020-10-12
        • 1970-01-01
        • 1970-01-01
        • 2014-04-25
        • 2015-02-16
        • 2012-09-25
        相关资源
        最近更新 更多