tags:

views:

72

answers:

3

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

+4  A: 

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 
    }
}
eugene y
my file has empty lines and there are some blank lines .
Tree
@SCNCN2010: You can add this test to the loop: `next if $array[$i] =~ /^\s+$/;`
eugene y
This wont work , when user is trying to add 'K'
Tree
A: 
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;
}
daxim
+1  A: 

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:~]$ 
dsm