awk help

Jim Trigg blaise at
Tue Apr 18 14:23:39 UTC 2017

On 2017-04-17 20:19, Polytropon wrote:
> On Mon, 17 Apr 2017 18:17:14 -0400, Ernie Luzar wrote:
>> Also can a csh $variable be used inside of an awk program?
> No directly. A sh (not csh!) variable is prefixed by $, but the
> awk program is typically enclosed in single quotes which prohibit
> the normal function of $FOO or ${FOO}; awk uses $ itself, for
> example as field identifiers like $0, $1, $2 and so on.
> If you'd have _no_ $ in your awk code, you could probably do
> something like this:
> 	#!/bin/sh
> 	FOO=100
> 	awk "BEGIN { print $FOO }"
> But of course, now you'll get problems using double quotes in awk.
> However, there is (at least) a way to deal with this problem: Prefix
> the data you're going to process with "special lines", let's say
> they start with #, a name (the "variable name", a =, and the "value".
> You can easily generate this as a temporary file from your "glue"
> script.
> I'm sure there are several other ways of doing this, but maybe those
> two examples can help or at least inspire you. :-)

The trivial way is:
   awk -v FOO=$FOO '{...}'

Note also that instead of embedding the awk script in the shell script 
you can make it a separate file and call it with
   awk -v FOO=$FOO -e script.awk

Jim Trigg

More information about the freebsd-questions mailing list