Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Awk in a shell script

Tags:

shell

awk

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,

like image 788
user1508893 Avatar asked Jul 11 '12 20:07

user1508893


1 Answers

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

awk "/$1/ {print NR}" $2 | head -n 1
like image 133
Lars Kotthoff Avatar answered Oct 03 '22 23:10

Lars Kotthoff