Link to home
Start Free TrialLog in
Avatar of shahrahulb
shahrahulb

asked on

delete line of file

is it possible to delete line of a file in perl without opening and closing a file
i mean i know to create a new file blah..... but that is a long way....

i want simple unix command to be used that can take care of it.

ex if file temp.txt contains:
james
robert half
todd minella

after executing my perl script the file temp.txt comtains
rahuk
todd minells
Avatar of shahrahulb
shahrahulb

ASKER

also how can i delete first n lines
Avatar of ozo
perl -MTie::File -e 'tie @array, "Tie::File", shift or die $!; splice @array,0,2,"rahuk" ' temp.txt

perl -MTie::File -e '$n=2;tie @array, "Tie::File", shift or die $!; splice @array,0,$n' temp.txt
DO you want to delete the line based on 'matching to a string' or on the basis of line numbers??

for deletion based on matching
sed '/string to match/d' temp.txt

for deletion based on
sed 'nd' temp.txt ##where n is the line number you want to delete.

but again, looks like you are inserting 'rahuk' also. Then it depends whether you want to go with Ozo's solution, or if you can, possibly do a
sed 's/initial/rahuk/' temp
#or
sed 'ns/.*/rahuk/' temp ##where n is the line number you want to replace


to delet 1st n lines

sed '1,nd' temp.txt
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Yeah, I was thinking that maybe the output redirection and renaming part could always be taken care of. But the author says 'I want simple Unix commands' and Perl solutions were already given.

And Tie::File also does rewrite the file on every modification.

perl -i -ne 'print if ($. > n)' temp.txt
#can also be used to remove the first n lines of the file. but again, even this opens/closes the file
if i try this in perl script:
system ("perl -i -pe '$_=\"\"if 1..7' out.txt");

i get error
syntax error at -e line 1, near "="
Execution of -e aborted due to compilation errors.
Atrnatively, you can do

{local $^I; local @ARGV=("out.txt");
while(<>) {$_="" if 1..7}
}
or
{local $^I; local @ARGV=("out.txt");
while(<>) {print if $.>7}
}
this worked

system("perl -i -pe '\$_=\"\"if 1..2' out.txt");