A File contains (a.txt)
# this is test file
Data: 15th may 2010
Records :
a
b
c
d
g
l
just consider if i want to add new record "f" - i want addit in betwen d and g
A File contains (a.txt)
# this is test file
Data: 15th may 2010
Records :
a
b
c
d
g
l
just consider if i want to add new record "f" - i want addit in betwen d and g
You can use Tie::File and treat the text file as array. This example assumes that there're no blank lines and initial text:
use Tie::File;
tie my @array, 'Tie::File', 'filename' or die $!;
my $rec = 'f';
for my $i (0..$#array) {
if (($array[$i] cmp $rec) == 1) {
splice @array, $i, 0, $rec;
last
}
}
use Tie::File ();
use List::MoreUtils qw(lastidx);
my $new_item = 'f';
{
my @file;
tie @file, 'Tie::File', 'a.txt'
or die "Could not open 'a.txt' for reading: $!";
splice @file, (1 + lastidx { $_ lt $new_item } @file), 0, $new_item;
}
in one line:
perl -le 'print for(sort((map {chomp; $_} (<>)), "f"))' < infile > outfile
You obviously need to process the headers beforehand, but the technique is pretty clear
For example:
[dsm@localhost:~]$ perl -le 'print for(sort((map {chomp; $_;} (<>)), "f"))' <<EOP
> x
> v
> b
> m
> p
> o
> l
> j
> k
> EOP
b
f
j
k
l
m
o
p
v
x
[dsm@localhost:~]$