【问题标题】:Removing carriage returns on the line prior to match (using sed, tr or awk)在匹配之前删除行上的回车(使用 sed、tr 或 awk)
【发布时间】:2012-12-10 13:54:41
【问题描述】:

我正在寻找一种方法来删除 sed 匹配行之前上的回车符。例如,我想删除任何“[”实例之前的回车符。

示例输入:

MESSAGE: Location
latitude
[-Pi/4,Pi/4]
longitude
[-Pi,Pi]
altitude
[10000,120000]

样本输出:

MESSAGE: Location
latitude [-Pi/4,Pi/4]
longitude [-Pi,Pi]
altitude [10000,120000]

任何使用 sed、tr 或 awk 的建议都将不胜感激。谢谢。

【问题讨论】:

    标签: sed awk grep tr


    【解决方案1】:
    #!/usr/bin/awk -f
    BEGIN {
      RS = ""
    }
    {
      gsub(/\n\[/, " [")
    }
    1
    

    【讨论】:

      【解决方案2】:

      使用 awk:

      awk 'NR == 1 {previous = $0}
           NR > 1 && $0 ~  "^[[]" {previous = previous $0}
           NR > 1 && $0 !~ "^[[]" {print previous; previous = $0}
           END{print previous}' your_file.txt
      

      【讨论】:

        【解决方案3】:

        这可能对你有用(GNU sed):

        sed '$!N;s/\n\[/ [/;P;D' file
        

        【讨论】:

          【解决方案4】:

          你可以使用 Perl:

          use warnings;
          use strict; 
          
          my $p; 
          
          while (<>) {
            if (/^\[/) {
              chomp $p; 
              print "$p $_";
              undef $p;
            } else {
              print $p if defined $p; 
              $p = $_; 
            }
          }
          

          或者从命令行:

          perl -lane ' if (/\[/) { print "$p $_"; undef $p} else { print $p if defined $p; $p = $_; }' input
          

          【讨论】:

          • 因为我正好在写一个perl脚本,所以这个方案最适合我的需要。谢谢。
          【解决方案5】:

          快速搜索会产生此帖子https://stackoverflow.com/a/1252191/722238 的结果。

          使用该帖子中的解决方案解决您的问题,答案如下:

          sed ':a;N;$!ba;s/\n\[/ [/g' yourinput.txt

          【讨论】:

            猜你喜欢
            • 2012-08-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-02-27
            相关资源
            最近更新 更多