Re: xargs - is it possible to take each argument in to xargs and use in sed against a file?

From: Stephane Chazelas (stephane_at_artesyncp.com)
Date: 08/19/05


Date: 19 Aug 2005 20:16:10 GMT

On 19 Aug 2005 12:56:46 -0700, Dundonald wrote:
[...]
> awk < $file '
> /$criteria/ && FNR > 1 {
> print last_line
> }
> {
> last_line = $0
> }'

You need to have the shell pass the variable to awk.

A good way to do this is making the variable an environment
variable have use awk's special ENVIRON associative array.

criteria_ENV=$criteria awk < "$file" '
  $0 ~ ENVIRON["criteria_ENV"] {
    print last_line
  }
  {
    last_line = $0
  }'

You need a POSIX conformant awk. That should be fine on every
recent Unices, except on Solaris where you need to make sure
/usr/xpg4/bin/awk is used and not the legacy /usr/bin/awk.

An other solution is to pass it as an argument and use the ARGV
special array in awk. There are other solutions using the -v
option of awk or the old var=value awk argument convention, or
have the shell expand the value of the variable within the awk
code argument, but none of them are suitable for a regexp as
$criteria is as they won't work if special characters are
present in the variable (and those special characters are often
found in regexps).

-- 
Stephane


Relevant Pages

  • Re: Weirdest shell behavior ever...
    ... The shell is an environment to call tools from, ... just use a text processing tool like awk. ... the usage environment allows my choice of any language, ...
    (comp.unix.shell)
  • Re: Weirdest shell behavior ever...
    ... The shell is an environment to call tools from, ... just use a text processing tool like awk. ... the usage environment allows my choice of any language, ...
    (comp.unix.shell)
  • Re: xargs - is it possible to take each argument in to xargs and use in sed against a file?
    ... Stephane Chazelas wrote: ... > You need to have the shell pass the variable to awk. ... > present in the variable (and those special characters are often ...
    (comp.unix.shell)
  • Re: awk instead of shell?
    ... I like shell for its ability to directly interact with the filesystem via the tools cp, cd, rm, mv, etc. ... However, shell can be very slow (and awk, on the contrary, seems very fast to me) and also, shell misses some idioms, like associative arrays. ... shell is an environment for calling tools. ... Use shell to sequence and provide an environment for the calls to those tools. ...
    (comp.lang.awk)
  • Re: [9fans] awk, not utf aware...
    ... If the shell that awk is running is PDKSH, ... KSH_VERSION exists in the environment, ... And the problem is precisely that the environment under which awk run ...
    (comp.os.plan9)