簡體   English   中英

使用輸入文件行號寫入多個輸出文件

[英]Write to multiple output files using input file line numbers

是的,我知道標題可能不是很清楚。 如果您有更改建議,請告訴我。

這是我的問題:我有一個文件(我們稱為File_1),其中有幾行,每一行都是一個句子。

例如:File_1內容:

*Line 1*: I'm very happy today.
*Line 2*: We're going to the cinema.
*Line 3*: I'll write on stackoverflow today!

等等..

我的問題是,如何從每一行的內容創建多個文件? 所以對於前。 file_1將被拆分為:

*Line_1_content.txt* : I'm very happy today.
*Line_2_content.txt* : We're going to the cinema.

等等...

我真的不知道該怎么辦。 我從來沒有遇到過這種問題。 感謝您的幫助。

use strict;
use warnings;
use autodie;

while ( <> ) {
    open my $fh, '>', "${.}.txt";
    print $fh $_;
}

$. 對應於當前行的編號。

您可以這樣調用該程序: perl prog.pl your_file

如果我正確理解問題的話:

use strict;
use warnings;
use autodie;

open(my $fh, '<', 'example.txt');
while (my $line = <$fh>) {
  open(my $line_fh, '>', "line_${.}_file.txt");
  print $line_fh $line;
  close($line_fh);
}
close($fh);

應該做你想做的。

(盡管這樣做可能不像注釋所指出的那樣有意義)

您甚至不需要程序:-)

perl -ne 'open my $fh, ">", "Line_${.}_content.txt"; print $fh $_"' your_file_here

也許,

perl -pe 'open my $fh, ">", "Line_${.}_content.txt"; select $fh' your_file_here

暫無
暫無

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

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