awk help

Polytropon freebsd at edvax.de
Tue Apr 18 14:49:41 UTC 2017


On Tue, 18 Apr 2017 10:23:38 -0400, Jim Trigg wrote:
> 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.
> [snip]
> > 
> > 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 '{...}'

Thanks for the reminder - it's really a very comfortable way!
I should be re-readinging the manpage from time to time to
remind me of this nice feature.



> 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

Quick addition: The form is

	awk -v FOO=$FOO -f script.awk

It's -f, not -e. :-)





-- 
Polytropon
Magdeburg, Germany
Happy FreeBSD user since 4.0
Andra moi ennepe, Mousa, ...


More information about the freebsd-questions mailing list