Friday 14 June 2013

Perl examples

1) A perl program to read a line  from standard input and  output each words entered using foreach.

#!/usr/bin/perl

$str1 = <STDIN>;

chomp $str1;

$count =1;

foreach $chr1 (split( //,$str1)){

print "\n word $count = $chr1";

$count++;

}

2)  A perl Program to reverse an entered  input of line.

a) Reverse the line of string as a whole.

b) reverse each words in the line

#!/usr/bin/perl

print "\n enter string";

$var1 = <STDIN>;

print "\n enter string";

$var2 = <STDIN>;

$rev1 = reverse($var1);

$rev2 = join ( " ",reverse split(" ",$var2));

print "\n reverse of $var1 = $rev1";

print "\n reverse of $var2 = $rev2";


3)   Perl program containing   substitution of expressions containing variables within patterns.

#!/usr/bin/perl

$no = 25;

$str1 = 'MY NUM IS $no';

$str2 = 'MY NUM INTO 2 IS $no';

$str1  =~ s/\$([a-z]+)/${$1}/g;

$str2  =~ s/\$([a-z]+)/${$1} * 2/eg;

print "\n $str1";

print "\n $str2";


4)Perl program to check whether input number is a natural number or integer.

#!/usr/bin/perl

$str = <STDIN>;

if ( $str =~ /^\d+$/ || $str =~ /^[0-9]+$/)

{

print "\nnatural number";

}

elsif ( $str =~ /^[+-]?\d+$/ || $str =~ /^-?\d+$/)

{

print "\nInteger";

}

else

{

print "\nnot an integer"

}



5)Perl program to add or subtract days from an entered date in YYYY-MM-DD format.It requires the Date::calc module.

#!/usr/bin/perl

use Date::Calc qw(Add_Delta_Days);

print "\nenter date in YYYY-MM-DD  ";

$dt = <STDIN>;

print "\nEnter days to add or -days to subtract  ";

$of = <STDIN>;

@darr = split("-",$dt);

$yr  = $darr[0];

$mon = $darr[1];

$ddi = $darr[2];

printf( "\nnew date  = %04d-%02d-%02d",Add_Delta_Days($yr,$mon,$ddi,$of) );


6) A perl program to print no of days, hours, minutes & seconds between two given  days

#!/usr/bin/perl

use Date::Calc qw(Delta_Days Delta_DHMS);

@date1 = (2004,03,13);

@date2 = (2003,12,15);

$ddiff = Delta_Days(@date2,@date1);

print "\n The days between the two dates $ddiff";

@dtim1 = (2005,06,17,14,36,17);

@dtim2 = (2005,06,18,11,19,35);

@dtimdiff = Delta_DHMS(@dtim1,@dtim2);

print "\n $dtimdiff[0] days $dtimdiff[1] Hrs $dtimdiff[2] Mins $dtimdiff[3] Secs";

.


7) A Perl program to add  a specified days,hours,minutes,secinds to a given date and time.

#!/usr/bin/perl

use Date::Calc qw(Add_Delta_DHMS);

print "\nenter Date & Time in YYYY-MM-DD-HH-MI-SS  ";

$dt = <STDIN>;

print "\nEnter duration to add in DAYS,HRS,MIN,SS   ";

$of = <STDIN>;

@dtmarr = split("-",$dt);

$yr  = $dtmarr[0];

$mon = $dtmarr[1];

$ddi = $dtmarr[2];

$hh = $dtmarr[3];

$mi = $dtmarr[4];

$ss = $dtmarr[5];

@durarr = split(",",$of);

$days = $durarr[0];

$hrs = $durarr[1];

$mins = $durarr[2];

$secs = $durarr[3];

printf( "\nnew date  = %04d-%02d-%02d %02d:%02d:%02d",Add_Delta_DHMS($yr,$mon,$ddi,$hh,$mi,$ss,$days,$hrs,$mins,$secs) );


8) A perl program to read a paragraph into an array and then print a particular line.

#!/usr/bin/perl

@para = (<<"INPUT" =~ m/^\s*(.+)/gm);

It was a day, long and hectic,

the day which I slogged more than ever

but got no reward and no accolades.

INPUT

print "\n $para[1]";


9) A perl program showing different ways of  storing variables in array.

#!/usr/bin/perl

@arr1 = "what are you doing";            #strores entire string as one element;

@arr2 = ("what","are","You","doing");   # stores quoted strings as individual elements

@arr3 = qw (what are you doing ?);         # stores individual words as elements

print "\n $arr1[0]";

print "\n $arr1[2]";

print "\n $arr2[2]";

print "\n $arr3[2]";

10)A perl progrm to store output of Unix ls command into an array.
#!/usr/bin/perl

@arr1 = qx(ls);

print "$arr1[0],$arr1[1],$arr1[2]";

11) A perl program to reduce the  length of an array using $#ARRAY.

#!/usr/bin/perl
@vararr = qw(This is an array);

$x = $#vararr;
print "\n|@vararr| length = " . ($x + 1);
$#vararr -= 1;
$x = $#vararr;
print "\n |@vararr| - length = " . ($x + 1);

PL/SQL examples

PL/SQL examples


1) A PL/SQL  block to check whether value entered by user is present in a list

set serveroutput on;

declare

x char(10);

y number(5);

z date;

BEGIN

dbms_output.put_line('ENTER A VALUE');

x := '&x';

dbms_output.put_line('ENTER another value');

y := &y;

IF x in ('2','4','hi')  then

dbms_output.put_line('FOUND');

END IF;

END;

/





2)PL/SL block  that formats numbers(floating point).

set serveroutput on;

declare

n1 number(6,2);

n2 number(6,2);

n3 number(6);

n4 number(4,-1);  --rounded of to 10

n5 number(4,-2);  -- rounded of to 100

n6 number(1,4);  -- rounded of to 1/10000

BEGIN

n1 := 2014.5;

n2 := 233.465;

n3 := 234.6;

n4 := 1657;

n5 := 1457;

n6 := 1/3845;

dbms_output.put_line('N1 = '||n1);

dbms_output.put_line('N2 = '||n2);

dbms_output.put_line('N3 = '||n3);

dbms_output.put_line('N4 = '||n4);

dbms_output.put_line('N5 = '||n5);

dbms_output.put_line('N6 = '||n6);

END;

N1 = 2014.5

N2 = 233.47

N3 = 235

N4 = 1660

N5 = 1500

N6 = .0003

PL/SQL procedure successfully completed.



3) A PL/SQL program that compares a CHAR and a VARCHAR2 variable with leading spaces.

declare

d1 varchar2(12); 

d2 char(12); -- ADDS SPACE CHARACTERs AT THE END

BEGIN

d1 := 'definitions';

d2 := 'definitions';

IF d1 = d2 then

dbms_output.put_line(' equal');

else

dbms_output.put_line(' not equal');

END IF;

END;

/

4) PL/SQl block to concatenate two variables values.
set serveroutput on;

DECLARE

x number(5);
y char(5);
z char(15);

BEGIN
x :=&x;
y :='&y';

z := x|| ' and '||y;
DBMS_OUTPUT.PUT_LINE(z);
END;
/

5)PL SQL Raise Application error example

SET SERVEROUTPUT ON;
DROP TABLE BILL_PAID;
CREATE TABLE BILL_PAID (
CUST_ID VARCHAR2(6),
BILL_DATE VARCHAR2(10),
BILL_AMOUNT NUMBER(10,4)
);


DECLARE

CUT_OF_DATE VARCHAR2(10) := '2014-01-05';
cid BILL_PAID.CUST_ID%TYPE;
DUE_DATE_EXCEEDED EXCEPTION;
PRAGMA EXCEPTION_INIT(DUE_DATE_EXCEEDED, -20006);

PROCEDURE pay_bill ( cust VARCHAR2 , dt  VARCHAR2, amount NUMBER) IS
 BEGIN
 
    COMMIT;
    IF  TO_DATE(dt,'YYYY-MM-DD')  > TO_DATE( CUT_OF_DATE,'YYYY-MM-DD' ) THEN

     RAISE_APPLICATION_ERROR (-20006,'BILL PAID AFTER DUE DATE');
  
   END IF;
   INSERT INTO BILL_PAID VALUES (cust,dt,amount);
END  pay_bill;

BEGIN
cid := 'J54677';
pay_bill(cid,'2013-12-30',1450.50);

cid := 'J54678';
pay_bill(cid,'2014-01-12',1320.00);  --will cause exception.

cid := 'J54642';
pay_bill(cid,'2014-01-05',750.50);

EXCEPTION
WHEN DUE_DATE_EXCEEDED THEN
DBMS_OUTPUT.PUT_LINE ('PENALTY CHARGED FOR CUSTOMER ' || cid);
DBMS_OUTPUT.PUT_LINE ('ERRNO = '|| SQLCODE || ' ERROR MSG IS ' || SQLERRM);
END;
/


Monday 3 June 2013

mail/mailx



mail/mailx/ 

unix mail utilities mail or mailx can be used to send mails to  users within a machine, a remote machine or web users using a relay server.

Example1)
To end mail to user hradmin on the machine v_serv1
/home/gadm$ mail x –v  -s “intimation”  hradmin@vserv_1  <mail_content_file
Here  the text “intimation”after –s  is the subject and mail_content_file contains mail body.

Example2)
Configurations for sending external mails through a relay server(eg IBM LOTUS) .
1)make an entry of mail relay server in /etc/mail/sendmail.cf file(can be done from root login)
vi /etc/mail/sendmail.cf
DS<mail relay server name>  ->add your mail server hostname in domain form(eg: mailserver.cbbs.net)

2)  edit /etc/hosts file and make an entry  of mail relay server.
10.5.6.34     <mail_svr_hostname>    <domain_name>
Also If your hostname contains only IP and plain hostname like
10.234.45.56  <my_hostname>,
Add another column  to make your hostname have a valid domain name(eg .com) otherwise you will get “hostname not qualified” error.
10.234.45.56  <my_hostname>   <my_hostname@<my_domain>

Ask your mail admin to add this hostname as a qualified  hostname  for receiving mails from.

3) stop and start the sendmail daemon.
stopsrc -s sendmail
startsrc -s sendmail -a “-bd -q30m”

Now you can send external mails using mailx command as follows.(AIX)
mailx  -v -s “<subject>” -r “< sender_name>”  -c  ”<cc_address(es)>”  <to_address>  < content_attach
here
“<subject> “         Is a quoted text   received  under subject(quoting is must when there is space in the text.
<sender_name>     Is the  name of the sender as seen by the recipient. If it is not used the recipient will see the sender as your <default user_name@domain.com>.
”<cc_address(es)>  Refer to those addresses to whom you need to send the copies of this mail to.
“<to_address>     Actual recipient address.
content_attach    A file containing body of the mail and encoded attachments.

A file like conetent_attach can be formed by using the uuencode command. For example if you hava a content file named  c_mail_body.txt  and an attachment  /home/v_admin/pdf_archive/trans_list.pdf  file   to send .
Uuencode  /home/v_admin/pdf_archive/trans_list.pdf   trans_list.pdf    >> c_mail_body.txt 
Now the file c_mail_body.txt   will contain both mail contents and attachment. You can use this file  to input  as content_attach  file  in the mailx  syntax.
mailx  -v -s “<subject>” -r “< sender_name>”  -c  ”<cc_address(es)>”  <to_address>  < c_mail_body.txt 





Thursday 25 April 2013

AWK Examples

1) An awk script which performs arithmetic.

awk '{

x = 3; y = 3;

print ($1/7) + ($2 - y)/x

z = $2 - 4;

print z

}'   file_1.txt

2) awk script to print the  filename  and its size and  finally total size occupied by all files.

ls -lrt | awk 'BEGIN { c = 0; siz = 0;print FILENAME BYTES}

NF == 9 && /^-/

{

print $9 " " $5;c++;siz += $5

}

END{

print "\nTOTAL COUNT = " c "\nTOTAL SIZE = " siz

}' 



3) consider a file(name_addr.txt)  containing names and addresses with records seperated by a blank line and fields seperated by newline.

kaushik

nayak

dl hsg socty

vashi

jose

dmello

ms clny

blore

reema

j l

highway rd

seattle

awk command to extract only first name from this file will be

awk 'BEGIN{FS ="\n";RS=""}

{

print $1

}' name_addr.txt


4)awk command to count the total number of blank lines in a file.

awk ' /^$/

BEGIN{ c = 0}

{

print x += 1

}

END

{

print c

}'  file_cont_blkline.txt


5) An awk script to count the total number of occurences of a pattern.

awk -v ptr=0003  'BEGIN{c = 0}{c += gsub(ptr," ",$0) }END{print c} ' sql2.txt

#here the pattern to count is '0003'  whose value is passed through variable ptr.

6) An awk program to split output of netstat command into IP and port for a specific port .

netstat  -an | awk '$4 ~ /.1521$/ {split($5,arr1,".");print "IP = " arr1[1]"."arr1[2]"."arr1[3]"."arr1[4] "|PORT = "arr1[5]}'

7) an awk program to print lines between two patterns (pattern ZO and a blank line)
awk '$0 ~ /ZO/,/^$/{ print $0}' select_all_bRS.txt

8)An awk program to write conditional output  to multiple files .
awk '{ if ($1 ~ /2013/ ){ print $0 > "date.txt"} else if ( $3 ~ /Branch/ ) {print $0  >"brch.txt"} }' branch_dt.txt

9) An awk script showing the use of next.
awk '$1 == "20130426" && $7 == "04060" && substr($2,1,2) == 10  {printf( "%s diff = %d \n",$0,$4 - $2);next }{print}' level_2.txt
#if next is not used then $0 will again be printed by  {print}.next skips the record

Sunday 29 January 2012

xargs


xargs
Xargs  is a command which can pass arguments from the output of one command to another. It can run multiline commands by passing arguments in a single file. The  most important feature is that it  creates a  list of arguments to be passed to the command and runs them.
Example1)
Consider that you have many files  and  each  have to be  renamed  with a common subscript letter.

/home/Krishna $ ls    account_[0-9].txt
account_4
account_5
account_7

Then to rename  all these files  as  < filename>_old  , use xargs as follows.

/home/Krishna$ ls  account_[0-9].txt  | xargs  -I  { }   mv   { }   { }_prev
/home/Krishna $ls    account_[0-9]*
account_4_prev
account_5_prev
account_7_prev
..

Here, xargs passed the output of ls, which is  a list  as  an argument list which is denoted by 
‘{  }’   to  the  mv  command .the  the entire line can be reconstructed as
mv  account_4   account_4_prev
mv   account_5  account_5_prev
….
..

Example2)
On few occasions, many unwanted processes  of a common type  may be running and  it is necessary to kill all of them without killing any other  process. One method would be to kill all of them with their individual PIDs, but  it may be not possible to do this in scripts, xargs does the job.

When  it is required to kill all processes run by your login name that have names containing  ftp in it,use
ps  -fu    $LOGNAME  |  grep  ftp  |  awk  ‘{ print  $2 }’  | xargs  -I   { }   kill  -9  { }


Example 3)
 You want to copy  a large number of  files  into  a directory  placing all the filenames  in a list file.
Consider a file containing  list of all the filenames .end line contains the destination directory

/home/Krishna$ cat   candidates_logs.txt
Arjuna.log
Yudhistir.log
Bhim.log
Nakul.log
Sahadev.log
..
/var/tmp/logs

You want to copy all these files to a directory  /var/tmp/logs with timestamp. use  xargs as follows.

/home/Krishna$ xargs   cp  –p  <  candidates_logs.txt
The command  structure created by xargs was
cp  -p   Arjuna.log  Yudhistir.log  Bhim.log  Nakul.log  Sahadev.log    candidates_logs.txt

This avoided the typing of all the files in an entire line. You may use this form of xargs in scripts where it is easier to make the list file using  simple echo and  “>>” .


Example 4)
You are redirecting  output containing contents of a file to another and you want a delimiting character  after every  n words , where n is any natural number, use xargs as follows.
a point to note here is that  a word can be a single line if it contains  only one word per line.

/home/Krishna$  cat   Train-Time.list
S29        F             12           Mumbai_CST     Karjat                   7:00pm  
T113     F             12 (x)   Mumbai_CST     Thane                   7:04pm  
K95        S              9 (x)      Mumbai_CST     Kalyan                  7:06pm  
A59        S              9             Mumbai_CST     Ambernath         7:15pm  
BL39     F             12           Mumbai_CST     Badlapur             7:17pm  
T115     S              9 (x)      Mumbai_CST     Thane                   7:20pm  
N27       F             12           Mumbai_CST     Kalyan                  7:21pm  

You can use awk to delimit the fields with  a “|” or any other delimiting character, but  xargs can  perform it too.
/home/Krishna$ cat   Train-Time.list | xargs  –n1  | xargs   -I  { }  echo  “{ }|”
S29|       F|            12|         Mumbai_CST|   Karjat|                  7:00pm|  
T113|   F|            12|         Mumbai_CST|   Thane|                 7:04pm|  
K95|      S|            9|            Mumbai_CST|   Kalyan|                7:06pm|  
A59|      S|            9|            Mumbai_CST|   Ambernath         7:15pm|  
BL39|   F|            12|         Mumbai_CST|   Badlapur|            7:17pm|  
T115|   S|            9|            Mumbai_CST|   Thane|                                 7:20pm|  
N27|      F|            12|         Mumbai_CST|   Kalyan|                7:21pm|  

You can trim the ending  “|” character by using sed .

Here you could have also used values greater than 1 after  n  so that the character “|” might be inserted after   those  many   words instead of 1.

Example 5)
When running commands by  passing multiple arguments , it sometimes becomes necessary to interactively  ask you to run it for each argument as seen in the commands  cp  -i  and  mv  -i.
xargs  using  its  -p option, can perform this on any command you want to run  interactively.

Consider a case where you need to take  tar  of files in a directory  by adding  every file  interactively  into the archive file.

/home/Krishna$ ls  |  xargs   -p   -n 1   tar -cvf   /backup/ALL_KRISHNA.tar
tar -cvf   /backup/ALL_KRISHNA.tar  account_4_prev   ?...y
tar -cvf   /backup/ALL_KRISHNA.tar  account_5_prev   ?...y
tar -cvf   /backup/ALL_KRISHNA.tar  account_7_prev   ?...n  ----------> your reply.
tar -cvf   /backup/ALL_KRISHNA.tar   jokes_old   ?...y
..
..

who


who
who  gives information regarding the users logged in the system, terminals, the  client IP addresses,the start and end times of previous logins and  their other  command  details. It s output is different from that of finger  command. “who” can give the  old details of users processes which  finger cannot


Example 1)
To know the details of users currently logged in a machine,  along with the header, use  who  command  with  –Hu.

home/kamlesh$who   -Hu
Name        Line                Time              Activity          PID                Hostname
kamlesh     pts/0       Jan 07 23:07    15:25        5206202             (169.173.25.64)
yadav         pts/1       Jan 08 07:40     0:22         3735576              (169.8.25.100)
stella          pts/2       Jan 08 14:47     0:35         5124214              (169.8.25.114)
jaffer          pts/5       Jan 08 16:17      .               4108396              (169.8.25.100)


Name
            Identifies the user's login name.
   
Line  
            Identifies the line name as found in the /dev directory. It is actually the terminal number  of   the user.

 Time
            Represents the time when the user logged in.
     
 Activity
            Represents the hours and minutes since activity last occurred on that user's line. A . (dot) here       indicates line activity within the last minute. If the line has been quiet more than 24 hours or has not been used since  the last system startup, the entry is marked as old.
     
 PID
            Identifies the process ID of the user's login shell.
    
 Hostname
            Indicates the name of the machine the user is logged in from.


Example2)
Who command gets the  information from  /etc/utmp file. If you wish it to use another file, specify the  filename  after who.

To get the output  from    /var/adm/wtmp.

home/kamlesh $who  -Hu    /var/adm/wtmp
Name                    Line                      Time                Activity                  PID              Hostname
kamlesh               pts/2                Dec 28 00:26                .                   930160        (indra)
sneha                  pts/2                  Dec 28 01:09                .                  156080        (indra)
krishna                pts/1                  Dec 28 02:33                .                  660214        (169.8.25.100)
krishna                pts/2                  Dec 28 02:37                .                  942618        (169.8.25.117)
justin                   pts/2                   Dec 28 02:51               .                 934590        (169.154.25.65)
varsha                 pts/2                  Dec 28 03:02                 .                  672308        (indra)
jaffer                   pts/2                   Dec 28 04:27               .                  267016        (169.8.25.100)
steve                  pts/3                    Dec 28 05:33               15:16           610818        (indra)
..
..
^c

All such  old sessions are displayed . so to keep a track on people who logged in and out ,the command helps.

Example 3)
To know the details of your  current session , ie the session from which you are running the command , an easier to remember command is used

home/kamlesh $ who am i
kamlesh    pts/1       Jan 08 01:30     (169.173.25.64)


Example 4)
In multi user work  environments, you may  require to know  whether your colleague is   logged in from a remote machine or  check continuously  whether  he/she has logged in ,
 Here is a script to do that.

#!/usr/bin/ksh
while [ 1 ]
do
who|grep  10.120.245.60
if [ $? -eq 0 ]
then
      while [ 1 ]
      do
      echo "\a Logged in"
      sleep 1
      done
fi
echo "Not logged in yet"
sleep 5
done