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

2024-09-26 04:55:57 发布

您现在位置:Python中文网/ 问答频道 /正文

要在与regexp匹配的每一行上方添加一个空行,可以使用:

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

但是我想添加一个空行,不是上面的一行而是上面的两行匹配我的regexp。

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

以下是文本格式的片段:

random info (belongs to previous business)
business name
business address

例如:

Languages Spoken: English
Arnold's Cove, Nfld (sub To Clarenville)
Nile Road, Arnolds Cove, NL, A0B1N0

我想在公司名称上方加一行:

Languages Spoken: English

Arnold's Cove, Nfld (sub To Clarenville)
Nile Road, Arnolds Cove, NL, A0B1N0


Tags: toenglishnlbusinessregexplanguagesarnold空行
3条回答

更具可读性的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 = ();
    }
}

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

sed '/regexp/i\

$H
x'

基本思想是打印延迟一行的所有内容(x更改保持和模式空间-打印是隐式的)。这需要完成,因为在我们检查下一行是否与regexp匹配之前,我们不知道是否要插入换行符。

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

简单:

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'

相关问题 更多 >