By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,660 Members | 1,230 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,660 IT Pros & Developers. It's quick & easy.

Perl Script to Test for Condition

P: 1
Hi,

I have a file that contains the following...

hostMode=Standard
displayName=CL1-A-0
nickname=1A-G00
hostMode=Windows Extension
displayName=CL1-A-2
nickname=SERVER123_B20_S6_0

I have a perl script (Below) that reads the above file, and if it finds the instance of "hostMode=Standard" it prints it out, (this is just to prove my sytax works).
Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/perl
  2. open (FILE,"mp.txt") || die print "Can't Open File\n";
  3. while (<FILE>) {
  4.     $_=~ s/^\s+//;
  5.     if (/hostMode=Standard/) {print "$_";}
  6.                }
  7. close (FILE);
  8.  
What I'd like to do is... if "hostMode=Standard" is found, I'd like to jump 2 lines down in the file and test if the first character of "nickname=" is a string. If it is I'll print it out, if it's not I'll just loop again for the next occurance of "hostMode=Standard" and do the same. Any ideas?
Sep 1 '08 #1
Share this Question
Share on Google+
2 Replies


Ganon11
Expert 2.5K+
P: 3,652
If you do a regular expression over multiple lines and match for the "hostMode=Standard" string, a line containing whatever, and "nickname=", then capture whatever remains on that line, you can compare away.
Sep 1 '08 #2

nithinpes
Expert 100+
P: 410
To do a regular expression over multiple lines, you need to undefine $/ first to read entire file at once and use /g option in pattern match to do the match repeatedly.
Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/perl
  2. open (FILE,"mp.txt") || die print "Can't Open File\n";
  3. $/="";  # undefine input record separator
  4. while (<FILE>) {
  5. $_=~ s/^\s+//;
  6. while (/hostMode=Standard\n.+\n(nickname=(.).*\n)/g) {
  7. $f=$1;$ch=$2;
  8. print "$f" if($ch =~/[A-Z]/i);} #print if 1st character after 'nickname=' is alphabet
  9.  }
  10. close (FILE);
  11.  
Sep 2 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.