Thursday 21 November 2019

Converting Awk Script to Perl Script - Examples of a2p Unix Command

LPI Study Materials, LPI Certification, LPI Tutorials and Materials, Unix Command

Unix provides the a2p (awk to perl) utility for converting the awk script to perl script. The a2p command takes an awk script and produces a comparable perl script.

Syntax of a2p:


a2p [options] [awk_script_filename]

Some of the useful options that you can pass to a2p are:

-D<number>     Sets debugging flags.
-F<character>  This will tell a2p that awk script is always invoked with -F option.
-<number>       This makes a2p to assume that input will always have the specified number of fields.

For more options see the man pages; man a2p

Example 1:


The awk script which prints the squares of numbers up to 10 is shown below. Call the below script as awk_squares.

#!/bin/awk -f
BEGIN 
{
    for (i=1; i <= 10; i++) 
    {
        print "The square of ", i, " is ", i*i;
    }
exit;
}

Run this script using awk command; awk -f awk_squares. This will produce squares of numbers up to 10.

Now we will convert this script using the a2p as
a2p awk_squares > perl_squares

The content of converted perl script, perl_squares, is shown below:

#!/usr/bin/perl
eval 'exec /usr/bin/perl -S $0 ${1+"mailto:$@%22%7D'
if $running_under_some_shell;
# this emulates #! processing on NIH machines.
# (remove #! line above if indigestible)
eval '$'.$1.'$2;' while $ARGV[0] =~ /^([A-Za-z_0-9]+=)(.*)/ && shift;
# process any FOO=bar switches
$, = ' ';               # set output field separator
$\ = "\n";              # set output record separator

for ($i = 1; $i <= 10; $i++) {
    print 'The square of ', $i, ' is ', $i * $i;
}
last line;

Run the perl script as: perl perl_squares. This will produce the same result as the awk.

Example 2:


We will see an awk script which prints the first field from a file. The awk script for this is shown below. Call this script at awk_first_field.

#!/bin/awk -f
{
    print $1;
}

Run this script using awk command by passing a file as input: awk -f awk_first_field file_name. This will prints the first field of each line from the file_name.

We will convert this awk script into per script using the a2p command as
a2p awk_first_field > perl_first_field

The content of converted perl script, perl_first_field, is shown below:

#!/usr/bin/perl
eval 'exec /usr/bin/perl -S $0 ${1+"mailto:$@%22%7D'
if $running_under_some_shell;
# this emulates #! processing on NIH machines.
# (remove #! line above if indigestible)
eval '$'.$1.'$2;' while $ARGV[0] =~ /^([A-Za-z_0-9]+=)(.*)/ && shift;
# process any FOO=bar switches
$, = ' ';               # set output field separator
$\ = "\n";              # set output record separator
while (<>) {
    ($Fld1) = split(' ', $_, -1);
    print $Fld1;
}

Now run the perl script as: perl perl_first_field file_name. This will produce the same result as awk command.

Related Posts

0 comments:

Post a Comment