Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

script to comment a line

Status
Not open for further replies.
Jun 3, 2007
84
US
Hello everyone I am hoping that someone could please help me out with a problem that I am stuck trying to figure out. I am trying to write a script which will read/cat/ a file and doing so will comment out (add a # at the start of the line) when it finds a line that ends with the string xx.xx.xx.xx.

So the recap I am trying to write a script that will be run against a file and if the script finds the string xx.xx.xx.xx at the end of any line it will at a # sign at the beginning of that line to comment it out.

I am pretty new to programming and I was having trouble coming up with an easy way to do this using perl.

Any examples ideas would really help me out.

thanks,
 
Code:
open FH, "<file.txt";
open OP, ">newfile.txt";
while (<FH>) {
  if (/xx.xx.xx.xx$/) { #regex anchors to the end of the line, assumes no trailing spaces
     $_="#".$_;
     print OP $_;
  }
}
close FH;
close OP;

Should provide a starting point

Paul
------------------------------------
Spend an hour a week on CPAN, helps cure all known programming ailments ;-)
 
Code:
perl -pi.bak -e '$_ = "#$_" if /xx\.xx\.xx\.xx$/' filename.txt
 
or you could do it like that ^^^ :rolleyes:

Paul
------------------------------------
Spend an hour a week on CPAN, helps cure all known programming ailments ;-)
 
Pretty much the same as ishnids code but in script format:

Code:
#!/usr/bin/perl
use warnings;
$^I = '.bak'; #Use inplace editing. same as 'i.bak'
while (<>) {
  print (/xx\.xx\.xx\.xx$/) ? "#$_" : $_;
}

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top