On Mon, 24 May 2004, Paul Lalli wrote:
> On Mon, 24 May 2004, Sundaram Ramasamy wrote:
>
> > I want to check in file line start with HOSTNAME, then I want to
> > replcae HOSTNAME value to linux.com, if line is not there I want add
> > new line HOSTNAME=linux.com
> >
> > Using inplace editing I was not able to add new line.
> >
> > Here is my one liner inplace editing script
> >
> > perl -i.old -ne '$ne=0; if( /^\s*HOSTNAME\s*=/ ) {
> > s/=.*$/=linux.com/; $nx++; print $_; }else { print $_; } END { if( $nx
> > ==0 ){ $_="HOSTNAME=linux.com\n"; print $_; } }' network
>
> Your main problem is that when run via -i, perl selects STDOUT after the
> end of the implicit loop. perldoc perlrun gives the clue on how to do
> this correctly.
> (Other problems in your code involve using $ne one place and $nx another
> and doing more regular expression processing than you need to).
>
> perl -i.old -ne '$n++ if s/^(\s*HOSTNAME\s*)=.*/$1=linux.com/; print $_;
> if (eof && $n==0 ){ print "HOSTNAME=linux.com\n" }' network
If and only if you're willing to let the HOSTNAME line move in the file,
this might be a slightly less messy way of accomplishing your goal.
[untested]
perl -i.old -ne 'print unless /^\s*HOSTNAME\s*=/; print
"HOSTNAME=linux.com\n" if eof;'
(The caveat is that the modified file will always have the HOSTNAME line
at the end of the file, regardless of where it might have been in the
original)
Paul Lalli
|