代码之家  ›  专栏  ›  技术社区  ›  Dennis

外壳:在图案上方两行插入空白/新行

  •  6
  • Dennis  · 技术社区  · 17 年前

    sed '/regexp/{x;p;x;}'
    

    但我想加一个空行,不是 上面的线,但是 与我的正则表达式匹配的行上方的行。

    我要匹配的模式是地址行中的邮政编码。

    随机信息(属于以前的业务)

    营业地址

    例如:



    尼罗河路,阿诺兹湾,NL,A0B1N0

    我想在企业名称上方添加一行:

    语言:英语


    尼罗河路,阿诺兹湾,NL,A0B1N0

    6 回复  |  直到 6 年前
        1
  •  5
  •   Jukka Matilainen    17 年前

    更易读的Perl,并理智地处理多个文件。

    #!/usr/bin/env perl
    use constant LINES => 2;
    my @buffer = ();
    while (<>) {
        /pattern/ and unshift @buffer, "\n";
        push @buffer, $_;
        print splice @buffer, 0, -LINES;
    }
    continue {
        if (eof(ARGV)) {
            print @buffer;
            @buffer = ();
        }
    }
    
        2
  •  7
  •   ephemient    17 年前

    有点像你在sed中的原始方法:

    sed '/regexp/i\
    
    $H
    x'
    

    基本思想是打印所有延迟一行的内容( X 是否插入换行符。

    ($H只是一个技巧,可以打印最后一行。它将最后一行附加到保持缓冲区中,以便最终的隐式打印命令也输出它。)

        3
  •  3
  •   Hynek -Pichi- Vychodil Paulo Suassuna    17 年前

    sed '1{x;d};$H;/regexp/{x;s/^/\n/;b};x'
    

    描述一下

    #!/bin/sed
    
    # trick is juggling previous and current line in hold and pattern space
    
    1 {         # at firs line
      x         # place first line to hold space
      d         # skip to end and avoid printing
    }
    $H          # append last line to hold space to force print
    /regexp/ {  # regexp found (in current line - pattern space)
      x         # swap previous and current line between hold and pattern space
      s/^/\n/   # prepend line break before previous line
      b         # jump at end of script which cause print previous line
    }
    x           # if regexp does not match just swap previous and current line to print previous one
    

    编辑 :稍微简单一点的版本。

    sed '$H;/regexp/{x;s/^/\n/;b};x;1d'
    
        4
  •  2
  •   Tanktalus    17 年前
    perl -ne 'END{print @x} push@x,$_; if(@x>2){splice @x,1,0,"\n" if /[[:alpha:]]\d[[:alpha:]]\s?\d[[:alpha:]]\d/;print splice @x,0,-2}'
    

    如果我把你的文件放在这里,我就能得到你想要的。..它很难看,但你想要shell(即一行代码):-)如果我用完整的perl来做这件事,我可以清理很多东西,使其接近可读性。 :-)

        5
  •  1
  •   S.Lott    17 年前

    这是一种适用于Python的方法。

    import sys
    def address_change( aFile ):
        address= []
        for line in aFile:
            if regex.match( line ):
                # end of the address
                print address[0]
                print 
                print address[1:]
                print line
                address= []
             else:
                address.append( line )
    address_change( sys.stdin )
    

    这使您可以根据自己的喜好重新格式化完整的地址。您可以展开此项以创建定义 Address

        6
  •  0
  •   lothar    17 年前

    我试过了

    sed '/regexp/a\\n'
    

    但它插入了两行。如果这不困扰你,那就收下吧。

    echo-e“a\nb\nc”|sed'/^a$/a\n'

    b
    c

    编辑: 既然您声明需要在匹配的正则表达式上方插入两行,那么建议的正则表达式将无法使用。

    我甚至不确定它是否适用于sed,因为你需要记住过去的台词。听起来像是python或perl等高级语言的工作:-)