0

I am making a word list from all the words typed into a program that will be working with the text entered into it. I want to use a stream editor like sed or awk to search the first word of every line in a document and return the line number when a pattern -stored in a variable- is found. I have this much working correctly so far:

awk $1 '{print $1 " " NR""}' dictionary.txt | awk '/^**myWord** /' | cut -d" " -f2

However, I cannot figure out how to use a variable in place of "myWord". For example, I get only errors when I use:

read=searchWord

awk $1 '{print $1 " " NR""}' words.txt | awk '/^**$searchWord** /' | cut -d" " -f2
Stephen Rauch
  • 4,209
  • 14
  • 22
  • 32
XBuilder
  • 1
  • 1

2 Answers2

0

Variable expansion will not happen inside of a single quoted ' string. Try:

searchWord="myWord"
awk $1 '{print $1 " " NR""}' words.txt | awk '/^**'"$searchWord"'** /' | cut -d" " -f2
Stephen Rauch
  • 4,209
  • 14
  • 22
  • 32
0

Try awk -v

-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.
Ask and Learn
  • 1,865
  • 4
  • 25
  • 34
  • Note that this is not supported everywhere, I remember e.g. that the `awk` that came with OS X did not support this. – phk Jan 25 '17 at 06:37