2017-10-10 21 views
-1

我有一個文件包含許多部分,但我想刪除所有節除第A. ?例如:任何方法去除一些部分在文件或只是通過線被刪除線(Perl腳本)

Section A 
abcdefg 

Section B 
hijklmn 

Section C 
opqrstu 

任何Perl腳本都可以寫入以刪除B和C中的所有內容?

+5

是的,Perl腳本可以做到這一點。 –

+1

你有什麼嘗試?你有什麼問題?請告訴我們你的代碼。如果你沒有代碼,那麼堆棧溢出不是你問題的最佳位置。 –

回答

1

您可以使用段落模式按部分讀取文件,然後只需使用正則表達式匹配來驗證要保留的部分名稱。

perl -00 -ne 'print if /^Section A/' -- file 
0

@Choroba沒有給你這樣的一個襯墊,所以這裏是一個腳本版本

use strict; 
use warnings; 

local $/ = ""; 
open(my $in_fh, "<", "inputfile.txt") or die "unable to open inputfile.txt: $!"; 
open(my $out_fh, ">", "outputfile.txt") or die "unable to open outputfile.txt: $!"; 
while (<$in_fh>) { 
    print $out_fh $_ if /^Section A/; 
} 

close $in_fh; 
close $out_fh; 

這將打開文件inputfile.txt和段落模式讀取,發現Section A和純打印Section A作爲段成文件outputfile.txt

給人

Section A 
abcdefg 
結果
0

我一直認爲像這樣的程序如果堅持Unix過濾器模型會更有用 - 即它們從STDIN讀取並寫入STDOUT

#!/usr/bin/perl 

use strict; 
use warnings; 

local $/ = ''; # paragraph mode 

while (<>) { 
    print if /^Section A/; 
}