2010-07-29 62 views
1

我在文件中有一个源文本,并寻找将从此文件中取出第二个(或第n个 - 一般)行的代码并将其打印到一个单独的文件。如何使用Perl从第n行写入文件

任何想法如何做到这一点?

+0

你必须告诉我们一些关于文件格式。 你的意思是'行'还是你的意思是'专栏' - 如果'专栏',他们是如何划定的? – 2010-07-29 16:56:12

+0

按行我假设你的意思是行。 – xenoterracide 2010-07-29 17:53:03

回答

0

你总是可以:

  1. 阅读所有的文件中,并却为一个变量。
  2. 拆分在阵列
  3. 换行符和存储变量的索引1(第二行)的写入值或n-1个位置到单独的文件
-1

我认为这将做你想做的:

line_transfer_script.pl:

open(READFILE, "<file_to_read_from.txt"); 
open(WRITEFILE, ">File_to_write_to.txt"); 

my $line_to_print = $ARGV[0]; // you can set this to whatever you want, just pass the line you want transferred in as the first argument to the script 
my $current_line_counter = 0; 

while(my $current_line = <READFILE>) { 
    if($current_line_counter == $line_to_print) { 
    print WRITEFILE $current_line; 
    } 

    $current_line_counter++; 
} 

close(WRITEFILE); 
close(READFILE); 

然后,你把它想:perl的line_transfer_script.pl 2和将从file_to_read_from.txt写二号线到FIL e_to_write_to.txt。

+1

你应该总是使用词法文件句柄,手动跟踪行号在Perl中是笨拙和不必要的。 – Ether 2010-07-29 17:23:08

+0

也使用3 arg打开。 2 arg开放有问题。 – xenoterracide 2010-07-29 17:51:17

-1
my $content = `tail -n +$line $input`; 

open OUTPUT, ">$output" or die $!; 
print OUTPUT $content; 
close OUTPUT; 
+0

使用词法文件句柄和3 arg打开 – xenoterracide 2010-07-29 17:51:43

5

您可以用flip-flop operator和特殊变量$.(由..内部使用),它包含了当前的行号做本身在Perl:

# prints lines 3 to 8 inclusive from stdin: 
while (<>) 
{ 
    print if 3 .. 8; 
} 

,或者在命令行:

perl -wne'print if 3 .. 8' <filename.txt>> output.txt 

您也可以做到这一点没有的Perl:head -n3 filename.txt | tail -n1 >> output.txt

+0

+1,所以完美。 – Toto 2010-07-29 17:26:20

+0

所以,如果你想只在第二行,你可以取代与触发器运营线路: 打印,如果2。2 或 打印如果 耶($ == 2)? – coffeepac 2010-07-29 22:05:16

+0

@coffeepac:正确! – Ether 2010-07-29 22:07:06

0

使用这样script.pl> OUTFILE(或>> OUTFILE进行追加)

此使用是优选的全球文件句柄和2 ARG开放词法文件句柄和3 ARG开放。

#!/usr/bin/perl 
use strict; 
use warnings; 
use English qw(-no_match_vars); 
use Carp qw(croak); 

my ($fn, $line_num) = @ARGV; 

open (my $in_fh, '<', "$fn") or croak "Can't open '$fn': $OS_ERROR"; 

while (my $line = <$in_fh>) { 
    if ($INPUT_LINE_NUMBER == $line_num) { 
     print "$line"; 
    } 
} 

note:$ INPUT_LINE_NUMBER == $。

这是一个稍微改进的版本,可处理任意数量的行号并打印到文件。

script.pl <infile> <outfile> <num1> <num2> <num3> ...

#!/usr/bin/perl 
use strict; 
use warnings; 
use English qw(-no_match_vars); 
use Carp qw(croak); 
use List::MoreUtils qw(any); 

my ($ifn, $ofn, @line_nums) = @ARGV; 

open (my $in_fh , '<', "$ifn") or croak "can't open '$ifn': $OS_ERROR"; 
open (my $out_fh, '>', "$ofn") or croak "can't open '$ofn': $OS_ERROR"; 

while (my $line = <$in_fh>) { 
    if (any { $INPUT_LINE_NUMBER eq $_ } @line_nums) { 
     print { $out_fh } "$line"; 
    } 
} 
+0

不要为'$ fn'写''fn'''。 – tchrist 2010-11-01 18:07:01

+0

@tchrist为什么不呢? – xenoterracide 2010-11-03 13:38:45

+0

因为它是一个no-op,除非你有一个重载'q(“”)操作符的对象,或者它是一个非祝福或至少是非重载的引用,你希望通过字符串化来杀死类似'HASH(0x8039e0 )'。它只是混淆了事情。如果你想要'$ fn'中包含的字符串,只需说'$ fn'。 – tchrist 2010-11-03 13:48:54

相关问题