Mark Galeck
Mark Galeck

Reputation: 6395

how to pass an argument containing whitespace to a script containing gawk match()?

>gawk 'match("", "foo bar", junk)'

is a legitimate command, and I would like to pass the argument foo bar to it inside a shell script:

foobar.sh which has:

#!/bin/bash
gawk 'match("", "'$1'", junk)'

Does not work:

>./foobar.sh "foo bar"
gawk: match("", "foo
gawk:           ^ unterminated string

How to do it?

Upvotes: 1

Views: 53

Answers (2)

rici
rici

Reputation: 241891

You left out the quotes needed to avoid word-splitting:

gawk 'match("", "'"$1"'", junk)'

Without those quotes, the string is split into two words:

match("", "foo
bar", junk)

awk insists that the program be a single argument (the next argument will be treated as a filename), so that produces a syntax error, as observed.

This is not the best way to pass arbitrary strings into an awk script because it will fail if the string includes a quote or backslash. It is better to use the -v var=value command-line option to initialize an awk variable directly from a bash string, which does not involve actually parsing the string as part of an awk program. However, it is always useful to understand bash quoting.

Upvotes: 3

anubhava
anubhava

Reputation: 785721

It should be passed using -v option:

gawk -v arg="foo bar" 'match("", arg, junk)'

Upvotes: 4

Related Questions