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

T

Ting Wang

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
 
P

Paul Lalli

Ting said:
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.
Is there another way to do it (a one line Perl command)?

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
 
T

Ting Wang

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.
 
P

Paul Lalli

Ting said:
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.

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top