This question already has an answer here:

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:


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

marked as duplicate by steeldriver, Sundeep, Satō Katsura, heemayl, Michael Homer Jan 25 '17 at 8:04

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


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

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

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.
  • 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 6:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.