0

I am writing a shell script which calls an awk script and then I take some user input in the BEGIN using getline, and I save the input to some variables.

BEGIN {printf "What's the word?"
getline word < "-"
}

Now, one of these variables is called "word" and I want to use it in another pattern in the script to print all lines containing the word given. I tried something like this:

/(^| )word( |$)/ 

which will print all lines containing the word "word", and I know that it's not gonna work because it's not recognized as being a variable. I'd searched a lot and found patterns starting with

$0~

but it's not working either in my case. Is there a way I could pass a variable to this pattern and print all lines containing the word stored in the variable?

Lois2B
  • 111
  • 1
  • 16
  • Is there a reason you aren't using the pattern in [How do I use shell variables in an awk script?](https://stackoverflow.com/questions/19075671/how-do-i-use-shell-variables-in-an-awk-script)? – Charles Duffy Apr 18 '18 at 15:33
  • I know that the -v option can be used for variables, but that would pass it from the shell to the awk script, and I tried to read the input in the BEGIN section instead of the shell itself. – Lois2B Apr 18 '18 at 15:42
  • Frankly, doing the read from the shell rather than from awk strikes me as in most circumstances the sensible approach -- that way your awk script's input can be from a non-terminal source if need be. But... *shrug*, you know your runtime context better than I do, and orthogonal to the question asked here. – Charles Duffy Apr 18 '18 at 15:43

2 Answers2

0

If you use a BEGIN section to build a variable with your full pattern, you can refer to it later:

awk -v word="hello" '
  BEGIN {
    pattern = "(^|[[:space:]])" word "([[:space:]]|$)"
  }

  $0 ~ pattern { print $0 }
'

...that said, you don't even need to do that, if you don't mind the overhead of reconstructing the pattern for every line:

awk -v word="hello" '$0 ~ ("(^|[[:space:]])" word "([[:space:]]|$)") { print $0 }'

(Why [[:space:]] instead of ? That way tabs and other whitespace characters other than hex-20 vanilla spaces can also act as word separators).

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
0

another alternative is using the word boundary, which you can apply in the variable with some backslash escaping

 awk -v v="\\\y$word\\\y" '$0~v' file

not sure all awks support this though. Alternatively you can use \< and \> for the left and right boundaries.

karakfa
  • 66,216
  • 7
  • 41
  • 56