473,609 Members | 1,842 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

switching from bash to Perl

25 New Member
Hi,
I recently started using bash and wrote some code to find certain IPs and related stuff in the leases files by using grep
I am trying to switch to perl. I am a bigginer and trying to learn perl by reading stuff on net.
I am getting stuck at following point
I wrote in bash
grep $IP data061009 -A 6

Now in perl I am writing
@result= grep (/$IP/, $_) in a while loop.
How do I incorporate '-A 6' part in perl
Please help.
Nov 10 '06 #1
13 3561
miller
1,089 Recognized Expert Top Contributor
There is no perl equivalent functionality for grep by default. But you can add it programmaticall y. Per the grep --help documentation.

Expand|Select|Wrap|Line Numbers
  1.   -A, --after-context=NUM   print NUM lines of trailing context
  2.  

Here is the code you want scetched out:

Expand|Select|Wrap|Line Numbers
  1. my $infile = "data061009";
  2. open(IN, "$infile") or die "open $inFile: $!";
  3. my $A = 0; # Variable to keep track of last seen.
  4. my @results = grep {/$IP/ ? $A=6 : $A-- > 0} <IN>;
  5. close(IN) or die "close $inFile: $!";
  6.  
You could also do the same thing using a for loop to make it more readable. But that gives you exactly what you want.
Nov 10 '06 #2
Studentmadhura05
25 New Member
Hi, thanks a lot!! It really worked!! But they I have another basic question, how did it work? I mean I am trying to understand the code you sent...but with my limited knowledge of Perl ...I am not able to understand what exactly is happening there!!
I am also reading a book on Perl side by side....but honestly ....there is so much in it...and I dont know where to look for my difficulties and so on.
Is there any quick/ smart way to learn perl?
Thanks again!!
Nov 13 '06 #3
miller
1,089 Recognized Expert Top Contributor
I'm glad my code example worked, but I'm not going to teach you perl. That's not what the forums are for, and really wouldn't be a good use of either of our times. Here is the code that I posted to you in a more verbose form to make it more readable. The nice and bad thing about perl is that it truly gives you the ability to do things in many different ways. Some of them very compact, but definitely harder to understand for the beginner.

Expand|Select|Wrap|Line Numbers
  1. my $infile = "data061009";
  2. open(IN, "$infile") or die "open $inFile: $!";
  3.  
  4. # Dumbing Down these two lines of code:
  5. #my $A = 0; # Variable to keep track of last seen.
  6. #my @results = grep {/$IP/ ? $A=6 : $A-- > 0} <IN>;
  7.  
  8. my @results = (); # Accumulate content.
  9. my $trailing = 0;
  10.  
  11. while (my $line = <IN>) {
  12.     if ($line =~ /$IP/) {
  13.         # Match Found: Save Results, and queue for 5 more lines to save
  14.         push @results, $line;
  15.         $trailing = 5;
  16.     } elsif ($trailing > 0) {
  17.         # Trailing Content: Save Results, decrement counter by 1.
  18.         push @results, $line;
  19.         $trailing--;
  20.     }
  21. }
  22. # END Dumb Down
  23.  
  24. close(IN) or die "close $inFile: $!";
  25.  
This code should explain what is occuring logically. If you want to learn more about grep, regular expressions, the $_ variable, the ?: operator, and such, you'll just have to do more reading and scrounging for code examples. Also, a little time just playing around with code snippets always helps to learn what things do. But I learned perl the hard way, so I really don't know what else to suggest that would make the process easier for someone else.
Nov 13 '06 #4
Studentmadhura05
25 New Member
Thanks...!
Nov 14 '06 #5
Studentmadhura05
25 New Member
In bash I could access a part of a string by using [ : : ]
For example:
$string=booksho p;
new_string=${st ring:0:4)
echo $new_string

The code above would retrun
book

Is there any way I can do similar thing in Perl?
Please help.

Miller,
I have understood the ?: operator from our previous discussion. Please let me know if I am right,
1. if grep is successful, A is set to 6 , print the current line
2. if grep is not successful, decremet A , print the current line

This would print 6 lines after the line with the grep argument,
If the grep is not successful right in the start, A =1 and decrementing it would push it to 0, >0 condition not satisfied, so dont print current line.

Is that the right interpretation of the code?
Nov 15 '06 #6
miller
1,089 Recognized Expert Top Contributor
Is there any way I can access a part of a string in Perl?
Look at: http://perldoc.perl.org/functions/substr.html

my $A = 0;
my @results = grep {/$IP/ ? $A=6 : $A-- > 0} <IN>;
I have understood the ?: operator from our previous discussion. Please let me know if I am right,
1. if grep is successful, A is set to 6 , print the current line
2. if grep is not successful, decremet A , print the current line

This would print 6 lines after the line with the grep argument,
If the grep is not successful right in the start, A =1 and decrementing it would push it to 0, >0 condition not satisfied, so dont print current line.

Is that the right interpretation of the code?
Close, but not quite verbally correct:

1. if the pattern /$IP/ matches, then $A=6 is used as the condition for grep. The statement $A=6 sets $A to 6, and then returns true (6), so the line is added to @results.
2. if the pattern /$IP/ doesn't match, then $A-- > 0 is used as the condition for grep. The statement $A-- > 0 is treated as $A > 0 by grep, and then a decrement is done to $A after the value check. So if the pre decrement value of $A is greater than 0, that the line is also added to @results.

Again, it is a lot harder to write out what is happening in words, than it is to just write it out in perl. But thank you for trying. It sounds like you have a good grasp of what was going on there. The hardest part to understand being the operator precedence.

Warning more advanced, probably unneeded knowledge to follow

Your use of /$IP/ is probably not completely correct. I'm assuming that $IP is an ip address. So if $IP='192.168.1. 1', the pattern would be /192.168.1.1/. You might notice there is a problem with the above regular expression, namely the dots (.). That catches a lot more ip address than you probably intend, like 192.168.141.255 . Instead, you want the dots to be treated as literals, and there is an easy shortcut for you to do this.

Just use /\Q$IP\E/ as your pattern.

Try printing out "\Q$IP\E" to see what those escape sequences actually do. They come in handle in regular expression all the time when working with literals. You can read more about them at:

http://perldoc.perl.org/functions/quotemeta.html
http://perldoc.perl.org/perlretut.ht...racter-classes
Nov 16 '06 #7
Studentmadhura05
25 New Member
Thanks Miller! I am kind of getting a little hang of coding in perl. I hope I improve....
I managed to use the 'substr' and it worked.
I am trying now to do the coding to get functionality equivalant to '-B' option of grep in perl. I will get back to you if I get stuck again.:-)
Thanks a lot for pointing out the posiible problems of using just /$IP/ as pattern!!!
Thanks!
Nov 16 '06 #8
miller
1,089 Recognized Expert Top Contributor
I am trying now to do the coding to get functionality equivalant to '-B' option of grep in perl. I will get back to you if I get stuck again.:-)
Expand|Select|Wrap|Line Numbers
  1. grep --help
  2.   -B, --before-context=NUM  print NUM lines of leading context
  3.  
That's a very good challenge. It's pretty straight forward to do that, but it won't be nearly as clean algorithmically . Good luck.
Nov 16 '06 #9
Studentmadhura05
25 New Member
I got it!!!
I do not know how to copy paste the code from putty...so I am typing it out again here...so there might be minor typing errors...but the code worked!!
Here it is:

while (<IN>) {
push @previous3, $_;
shift @previous3 if @previous3 > 3;
@host= grep (/$hardware/, $_);
my $host = @host;

if ($host == 1) {
print @previous3;
}


What do you think?
Nov 16 '06 #10

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

Similar topics

1
7902
by: Goblin | last post by:
Hello i have a little code for updating somethink in my SQL database. I get the error: bash: /root/remstats.pl: /usr/bin/perl: bad interpreter: Permission denied Can someone tell me what's wrong? Or how i can fix that? Greets, Bert The code of the script: #!/usr/bin/perl
2
8986
by: Dmitry | last post by:
Hi folks! I need to find a way to switch to a different Unix user from within the Perl script that is currently ran unattended. Script must switch user in order to execute proper profile for different Data Base Instance and set corresponding environmental variables correctly. Script works fine for a single Data Base Instance. I need to be able to run it consecutively for several others instances. This requires login in as a different...
11
2988
by: Magnus Jonneryd | last post by:
Hi, I'm planning on writing a program that interactively is fed input via a shell (bash). I also want to be able to write a shell script that executes various commands related to my program. In short i want to provide input to a program using some (or all) of the functionality found in bash. It's mainly the format of the file I'm having trouble with. I wanted to be able to write something like this: #!/bin/bash for x in xs
2
12822
by: Bryan_Cockrell | last post by:
Hi World, I am extracting text from an ebcdic header using dd in the cygwin environment (bash/ksh) as below in order to rename the file to something intelligent. I'm using a specific string position here ($10) but the text I extract is sometimes in a different position in the header so I need to search for preceding text "LINE:" and then extract the next string, which is the info I'm interested in. So - using awk or sed (or perl if need...
16
3931
by: John Salerno | last post by:
Hi all. I just installed Ubuntu and I'm learning how to use the bash shell. Aside from the normal commands you can use, I was wondering if it's possible to use Python from the terminal instead of the normal bash commands (e.g. print instead of echo). My main reason for asking is that I like using Python for everything, and if I don't need to learn the bash 'language', then I won't just yet. Thanks.
4
3572
by: melmack3 | last post by:
Hello My PHP script executes many bash/cmd commands. Functions like "exec()" or "system()" cause that new bash/cmd session is started, the command is executed and the session is closed. Unfortunately it is very slow process so I would like to increase performance and open one bash/cmd session on the begin of my script and execute the commands such as in normal system opened bash/cmd window and close it
0
1288
by: sidd50 | last post by:
Hi, I need to fetch the data from database and based on the user type i have to start some service based on user type from withing my script. I am getting some syntax error that i am not able to resolve. It will be much appreciated if some one can help me out. Error block is followed by code block. Code block: sqlquery="sqlPlus << ENDCOMM \ SET ECHO OFF; \ SPOOL user_details.dat ; \ SELECT...
3
1545
by: suicidal pencil | last post by:
Hello! I won't lie, I'm new to Perl. I'm trying to switch variables in perl from '1' to '0', and somtimes '2', but it's not working correctly here's how I think a switch should be preformed: if ($input eq "switch them"){ $variable == 1;
10
4427
by: Isaac Gouy | last post by:
$ ./test_fail 1 Floating point exception - but this leaves 'somefile' zero size $ ./test_fail 1>somefile Floating point exception
0
8573
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8547
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8224
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6062
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5517
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4026
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4091
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2535
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1676
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.