2

I'm just trying to get started writing an awk script to test for inclusion in an array, however I seem to have a basic syntax error someplace.

#!/bin/bash


awk \
BEGIN {'myarray["foo"] = "bar" '} \
{' \
  print "$1" \
'} $1

If I take out the BEGIN line, then indeed the rest of the script works.

I have also tried it like this:

#!/bin/bash
awk \
{' \
  myarray["foo"] = "bar" \
  print "$1" \
'} $1

Here's the error I'm getting.

awk: syntax error at source line 1
 context is
     >>>  <<<
awk: bailing out at source line 1
1
  • 1
    not clear why you're doing {'myarray....'}. Normally you should just surround the whole awk script with one set of single quotes like awk 'BEGIN{ ...} { ..... } END {...} file > outFile`. You can get fancy with dbl-quotes to all allow shell vars to be visible, but @FredrikPihl 's advice is good. Good luck. Commented Dec 8, 2013 at 22:05

1 Answer 1

4

Try something like this:

#!/bin/bash

awk -v param="$1" '
BEGIN { myarray["foo"] = "bar"}
{
  print myarray["foo"]
  print param
}' $1

-v is the proper way to pass an variable into awks-domain:

-v var=val
       --assign var=val
              Assign  the  value  val to the variable var, before execution of
              the program begins.  Such variable values are available  to  the
              BEGIN block of an AWK program.

Example:

$ echo 1 > one_line_file

$ ./t.sh one_line_file 
bar
one_line_file
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.