How to pass bash parameter to awk script?

I have awk file:

#!/bin/awk -f
BEGIN {

}
{
        filetime[$'$colnumber']++;
}
END {
        for (i in filetime) {
                print filetime[i],i;
        }
}

And bash script:

#!/bin/bash
var1=$1
awk -f myawk.awk

When I run:

ls -la | ./countPar.sh 5

I receive error:

ls -la | ./countPar.sh 5
awk: myawk.awk:6:         filetime[$'$colnumber']++;
awk: myawk.awk:6:                   ^ invalid char ''' in expression

Why? $colnumber must be replaced with 5, so awk should read 5th column of ls ouput. Thanks.

Answers


You can pass variables to your awk script directly from the command line.

Change this line:

filetime[$'$colnumber']++;

To:

filetime[colnumber]++;

And run:

ls -al | awk -f ./myawk.awk -v colnumber=5

If you really want to use a bash wrapper:

#!/bin/bash
var1=$1
awk -f myawk.awk colnumber=$var1

(with the same change in your script as above.)

If you want to use environment variables use:

#!/bin/bash
export var1=$1
awk -f myawk.awk

and:

filetime[ENVIRON["var1"]]++;

(I really don't understand what the purpose of your awk script is though. The last part could be simplified to:

END { print filetime[colnumber],colnumber; }

and parsing the output of ls is generally a bad idea.)


The easiest way to do it:

#!/bin/bash
var=$1
awk -v colnumber="${var}" -f /your/script

But within your awk script, you don't need the $ in front of colnumber.

HTH


Need Your Help

When should the ViewModels call Services and Isolatedstorage

mvvm windows-phone-7 mvvm-light

I'm using the MVVM-Light toolkit and storing my ViewModelLocator in App.Resources. I noticed that my ViewModelLocator class gets created before the Application_Launching event gets fired, and acco...

ASHX and “Cannot use a leading .. to exit above the top directory”

c# asp.net .net-2.0

I have an ASHX into which I want to load a UserControl from a folder parallel to it. When I try to use a relative path using .., I get the exception, Cannot use a leading .. to exit above the top

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.