Glam Prestige Journal

Bright entertainment trends with youth appeal.

My script is:

#!/usr/bin/perl -w
my $line="1 2 3 4 5 6 7";
print $line;
my $thirdlast=`print $line |awk '{print $(NF-3)}'`;
print $thirdlast;

The output is:

1 2 3 4 5 6 7 awk: 0602-542 There is an extra ) character. The source line is 1. The error context is {print 201 1 >>> 201NF-3) <<< Syntax Error The source line is 1. awk: 0602-502 The statement cannot be correctly parsed. The source line is 1. awk: 0602-542 There is an extra ) character.

What is it complaining about? Anything wrong with my script? Couldn't understand why it says The source line is 1.

What fix is needed by my script?

3 Answers

You don't need to call awk inside your perl program, perl provides the necessary functions to perform such operation:

#!/usr/bin/perl -w
my $line="1 2 3 4 5 6 7";
my @tab = split(/\s+/, $line);
print $tab[-3],"\n";

This small program outputs: 5

3

A Sylvain pointed out, you really don't need to call awk from within perl since the latter can do anything the former can. However, to answer your original question, you need to i) escape the $ inside the awk, ii) correctly pass your Perl variable to the subshell you launch (print is something completely different in the shell). Something like:

#!/usr/bin/perl -w
my $line="1 2 3 4 5 6 7";
## Use echo, not print and escape the $ in $(NF-3)
my $thirdlast=`echo "$line" |awk '{print \$(NF-3)}'`;
print $thirdlast;

The same thing can be done with cut like so:

cut -d ' ' -F <field>

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy