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
1

2 Answers 2

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
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.
1
  • Note that this is not supported everywhere, I remember e.g. that the awk that came with OS X did not support this.
    – phk
    Commented Jan 25, 2017 at 6:37

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.