How to pass bash parameter to awk script?

I have awk file:

#!/bin/awk -f

        for (i in filetime) {
                print filetime[i],i;

And bash script:

awk -f myawk.awk

When I run:

ls -la | ./ 5

I receive error:

ls -la | ./ 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.


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

Change this line:




And run:

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

If you really want to use a bash wrapper:

awk -f myawk.awk colnumber=$var1

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

If you want to use environment variables use:

export var1=$1
awk -f myawk.awk



(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:

awk -v colnumber="${var}" -f /your/script

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


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# .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.