use one line Perl command to add a line at the begin of a file

use one line Perl command to add a line at the begin of a file

Post by Ting Wan » Wed, 14 Dec 2005 23:25:28


Hallo all,
I wanted to add a line (e.g #include "some.h") at the begin of all .c files
in a directory.
I try to change one .c file with one line Perl command

perl -i.org -p -e 'BEGIN{print "#include \"some.h\"\n";}'

But this doesn't work, "#include "some.h"" will be printed into STDOUT.
I did it with a 'long' Perl script:

my $f = shift;
my $fm = $f.".org";
`touch $fm`;
open F, $f or die "can not open file $f $!";
open FM, "> $fm" or die "can not open file $fm $!";
select FM;
print "#include \"some.h\"\n";
while (<F>)
{
print;
}
close F;
close FM;
`mv $fm tmp`;
`mv $f $fm`;
`mv tmp $f`;

Is there another way to do it (a one line Perl command)?


Thanks alot

Ting
 
 
 

use one line Perl command to add a line at the begin of a file

Post by Paul Lall » Wed, 14 Dec 2005 23:40:30


See the documentation for -i in perldoc perlrun, eof in perldoc -f eof,
and $. in perldoc perlvar:

perl -ni.org -e'print qq{#include "some.h"\n} if $. == 1; print; close
ARGV if eof;' *.c

Paul Lalli

 
 
 

use one line Perl command to add a line at the begin of a file

Post by Ting Wan » Thu, 15 Dec 2005 02:36:38

Thanks alot for your help.
$. is exactly what i want :).
And i found
perl -i.org -p -e'print qq{#include "some.h"\n} if $. == 1;'
works too.
 
 
 

use one line Perl command to add a line at the begin of a file

Post by Paul Lall » Thu, 15 Dec 2005 03:07:37


That will work if and only if you have exactly one file. Your original
email stated you wanted to work on *all* .c files in the directory.
This is why I told you to read up on
perldoc -f eof

Paul Lalli