Skip site navigation (1)Skip section navigation (2)
Date:      Tue, 18 Apr 2017 16:49:36 +0200
From:      Polytropon <freebsd@edvax.de>
To:        Jim Trigg <blaise@scadian.net>
Cc:        Ernie Luzar <luzar722@gmail.com>, freebsd-questions@freebsd.org
Subject:   Re: awk help
Message-ID:  <20170418164936.98e78648.freebsd@edvax.de>
In-Reply-To: <88bf3158d9f36b574df2fa15b8c0883a@scadian.net>
References:  <58F25A01.1060208@gmail.com> <7951DF71-5CD3-4B53-9CB4-13CAA8945983@huiekin.org> <58F4CD14.7090008@gmail.com> <c95e03d2-986d-3c3c-198a-a28ab862dc70@gmail.com> <58F53EEA.2030206@gmail.com> <20170418021926.8410148b.freebsd@edvax.de> <88bf3158d9f36b574df2fa15b8c0883a@scadian.net>

next in thread | previous in thread | raw e-mail | index | archive | help
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, ...



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20170418164936.98e78648.freebsd>