簡體   English   中英

Perl - 如何從文本文件中省略行?

[英]Perl - How to omit lines from a text file?

我有一個文本文件,我希望從文本文件中省略一些行,並使用該字符串創建一個新文件。 好消息是我的文本文件以包含“START”並以“END”結尾的行開頭我需要的文本塊。

例如,我的文本文件如下所示:

1
2
3
Start
4
5
6
End
7
8
Start
9
10
End

所需的 output 將是兩個字符串,我可以將 output 轉換為如下所示的文本文件:

Start
4
5
6
End
Start
9
10
End

我目前所擁有的:

open(RH, '<', $fileName) or die $!;

while(<RH>) {
    #print $_;
    chomp $_;
    if ($_ eq 'START') {
        $str = "$str"."$_\n";
    }
}

但我不確定如何繼續。

編輯:我使用以下方法回答了這個問題:

$cmd = q(awk '/Start/,/End/ {print}' foo.txt);
my $output = qx($cmd);
my @cards = split (/(?<=\End)/, $output);

您可以使用來自 AWK 的一些 Perl 遺產,然后執行此操作(假設您的文件名為 foo.txt)

perl -ne'print if /Start/../End/' foo.txt

表達式/Start/../End/表示“從匹配/Start/的第一行到匹配/End/的下一行。

awk 的等效代碼為

awk '/Start/,/End/ {print}' foo.txt
# Read the entire file into a string `$str`:
open my $fh, '<', 'file_name' or die "Can't open file $!";
my $str = do { local $/; <$fh> };
close $fh;

while ($str =~ m{\n(START\n.*\nEND)\n}msg) {
    # Do something with each START...END set of lines
    print "$str\n";
}

筆記:

  • 我不確定所有的細節。
  • local $/ ; 可能由類似undef $/;之類的東西來完成。
  • 調整括號以避免捕獲“開始”和“結束”。

使用 GNU grep

grep -Poz '(?ms)^Start.*?^End\n' in_file

在這里,GNU grep使用以下選項:
-P :使用 Perl 正則表達式。
-o :僅打印匹配項(每行 1 個匹配項),而不是整行。
-z :將輸入和 output 數據視為行序列,每行都以零字節(ASCII NUL 字符)而不是換行符結尾。 因此,您可以匹配輸入中的換行符。

(?ms) :啟用ms模式匹配修飾符,以允許多行匹配,並允許. 分別匹配換行符。

也可以看看:
grep說明書
perlre - Perl 正則表達式

使用..作為“觸發器”運算符。

# Switch to a lexical filehandle
# (as this is modern best practice)
open(my $rh, '<', $fileName) or die $!;

# Open an output filehandle
my $x = 1;
open my $out, '>', "$filename.out.$x" or die $!;

while(<$rh>) {
  print $out $_ if /Start/ .. /End/;

  # Open a new output file if we've seen 'End'
  if (/End/) {
    ++$x;
    open my $out, '>', "$filename.out.$x" or die $!;
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM