How do I append some lines from several text files to another one?
I have got nine text files in a directory, each has 1000 lines. I want to take the first 500 lines from each, then write all of them in order to another text file, and take the rest (the last 500 lines) from each one to do the same I do before.
awk '{if (NR<=500) {print}}' 1.txt > 2.txt # I do it 9 times, then I use cat to append.
awk '{if (NR>500) {print}}' 3.txt > 4.txt 开发者_JAVA百科
or
awk 'NR>500' 3.txt > 4.txt
I did it with awk, but I want to learn Perl instead.
In Perl $.
has line number of last accessed filehandle. In while ($. <=500 )
-cycle you can get wanted count of lines.
perl -e 'open(F1,">1.txt");
open(F2,">2.txt");
foreach (@ARGV) {
open(F,"<$_");
while(<F>) {
print F1 $_ if ($. <= 500);
print F2 $_ if ($. > 500);
}
close(F);
}
close(F1);
close(F2);' <FILES>
Your explanation could agree with your example more. But based on the idea that you want all 9000 lines to go into a single file.
I didn't know where you were going to specify your names, so I used the command line.
use English qw<$OS_ERROR>;
open( my $out_h, '>', $outfile_name )
or die "Could not open '$outfile_name'! - $OS_ERROR"
;
my @input_h;
foreach my $name ( @ARGV ) {
open( $input_h[ $_ ], '<', $name )
or die "Could not open '$name'! - $OS_ERROR"
;
}
foreach my $in_h ( @input_h ) {
my $lines_written = 0;
while ( $lines_written++ < 500 ) {
print $out_h scalar <$in_h>;
}
}
foreach my $in_h ( @input_h ) {
print $out_h <$in_h>;
}
close $out_h;
close $_ foreach @input_h;
open(F1,">1.txt");
open(F2,">2.txt");
open(F,"<$_");
while(<F>) {
print F1 $_ if ($. <= 500);
print F2 $_ if ($. > 500);
}
close(F);
close(F1);
close(F2);
i deleted foreach statement then it works, isnt that weird. thanks for ur help by the way..
精彩评论