Calling Awk in a shell script

后端 未结 4 1664
遥遥无期
遥遥无期 2021-01-18 19:32

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

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

The purpose i

4条回答
  •  爱一瞬间的悲伤
    2021-01-18 19:45

    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.

提交回复
热议问题