【问题标题】:trying to combine multiple lines between two two patterns in the same file试图在同一个文件中的两个两个模式之间组合多行
【发布时间】:2021-03-02 09:41:42
【问题描述】:

我正在尝试将两种模式之间的多行组合成一行,由空格分隔。但是,我需要保留两种模式前后的文字。

Input
Line 1
Line 2
Line 3
PATTERN 1
Line 4
Line 5
Line 6
PATTERN 2
Line 7
Line 8

Desired Output:
Line 1
Line 2    
Line 3
Line 4 Line 5 Line 6
Line 7
Line 8

我找到了许多使用 sed、awk 和 perl 组合多行的示例,但我找不到如何保持 PATTERN 匹配前后的文本不变的示例。谢谢。

【问题讨论】:

  • 欢迎来到 SO,请在您的问题上以代码的形式添加您的努力,这在 SO 上受到强烈鼓励。
  • 你是这样实际使用还是有多个匹配项?重叠匹配的可能性?

标签: perl awk sed


【解决方案1】:

这主要是 Perl 的“触发器”运算符的用途。

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

my @collect;

while (<DATA>) {
  chomp;
  # If we're between our markers...
  if (/^PATTERN 1/ .. /^PATTERN 2/) {
    # At the start marker, empty the array
    if (/^PATTERN 1/) {
      @collect = ();
    # At the end marker, print the array
    } elsif (/^PATTERN 2/) {
      say join ' ', @collect;
    # Otherwise, push the line onto the array
    } else {
      push @collect, $_;
    }
  # Otherwise, just print the line
  } else {
    say;
  }
}

__DATA__
Line 1
Line 2
Line 3
PATTERN 1
Line 4
Line 5
Line 6
PATTERN 2
Line 7
Line 8

为了便于开发,我在此处读取DATA 文件句柄。您需要将其更改为您已打开的某个文件句柄。

【讨论】:

  • 谢谢克罗斯先生。说我是新手未免太客气了。我的数据在外部文件中。当我像上面那样使用文件中的数据运行脚本时,它当然可以正常工作。我将您的脚本放在一个名为 perl.pl 的文件中,从“DATA”中删除行到文件末尾。我将数据放在一个名为 test.txt 的单独文件中。然后我输入以下内容:perl perl.pl test.txt > test1.txt。我收到了这个错误:名称“main::DATA”只使用了一次:perl.pl 第 9 行可能有错字。perl.pl 第 9 行未打开的文件句柄 DATA 上的 readline()。
  • 我想通了。非常感谢大家
【解决方案2】:

这取决于您在行中的阅读方式。如果你给我更多关于你想要做什么的信息,我可以给你一个更好的答案。

如果你一次读一个,这样就可以了。

while (my $line = <HANDLE>) {
  if ($line =~ m/PATTERN1/) {
    my @collection;
    while (my $inner = <HANDLE>) {
      if ($inner =~ m/PATTERN2/) {
        last;
      }
      else {
        push @collection, $inner;
      }
    }
    chomp @collection;
    print "@collection\n";
  }
  else { print $line; }

}

如果您将所有内容都放在一个字符串中并想就地替换它,请使用此正则表达式。

$text =~ s{^PATTERN1$(.*?)^PATTERN2$}{ my $t = $1; $t =~ tr/\n/ /; $t; }smg;

谢谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-30
    • 2023-04-04
    • 1970-01-01
    • 2022-01-08
    • 2017-06-10
    • 2015-04-14
    • 1970-01-01
    相关资源
    最近更新 更多