user1508893
user1508893

Reputation: 9813

Calling Awk in a shell script

I have this command which executes correctly if run directly on the terminal.

awk '/word/ {print NR}' file.txt | head -n 1

The purpose is to find the line number of the line on which the word 'word' first appears in file.txt.

But when I put it in a script file, it doens't seem to work.

#! /bin/sh

if [ $# -ne 2 ]
then
        echo "Usage: $0 <word> <filename>"
        exit 1
fi

awk '/$1/ {print NR}' $2 | head -n 1

So what did I do wrong?

Thanks,

Upvotes: 5

Views: 12290

Answers (4)

villaa
villaa

Reputation: 1239

you could also pass the value as a variable to awk:

awk -v varA=$1 '{if(match($0,varA)>0){print NR;}}' $2 | head -n 1

Seems more cumbersome than the above, but illustrates passing vars.

Upvotes: 2

Dennis Williamson
Dennis Williamson

Reputation: 360615

You should use AWK's variable passing feature:

awk -v patt="$1" '$0 ~ patt {print NR; exit}' "$2"

The exit makes the head -1 unnecessary.

Upvotes: 6

ruakh
ruakh

Reputation: 183544

In the shell, single-quotes prevent parameter-substitution; so if your script is invoked like this:

script.sh word

then you want to run this AWK program:

/word/ {print NR}

but you're actually running this one:

/$1/ {print NR}

and needless to say, AWK has no idea what $1 is supposed to be.

To fix this, change your single-quotes to double-quotes:

awk "/$1/ {print NR}" $2 | head -n 1

so that the shell will substitute word for $1.

Upvotes: 6

Lars Kotthoff
Lars Kotthoff

Reputation: 109272

Replace the single quotes with double quotes so that the $1 is evaluated by the shell:

awk "/$1/ {print NR}" $2 | head -n 1

Upvotes: 7

Related Questions