Bash 脚本 |带变量的 awk

Bash scripting | awk with ariables

作品:

repquota $HOME | awk "{if($3 > $MIN && $3 < $MAX )print}"

但是,如果我尝试将其插入到变量中,则它不起作用:

VARIABLE=`repquota $FULL_HOME | awk "{if($3 > $MIN && $3 < $MAX )print}"`

awk: {if( > 1572864 && < 302118056)print}

awk: ^ syntax error

使用新的命令替换语法$(command):

VARIABLE=$(repquota $FULL_HOME | awk "{if($3 > $MIN && $3 < $MAX )print}")

说明

来自man bash

   When  the  old-style  backquote form of substitution is used, backslash
   retains its literal meaning except when followed by $, `,  or  \.   The
   first backquote not preceded by a backslash terminates the command sub‐
   stitution.  When using the $(command) form, all characters between  the
   parentheses make up the command; none are treated specially.

当使用反斜杠时,双引号字符串中的 $var 没有转义,导致 $var 的值被替换,所以 awk 看不到 </code>,如你所料。</p> <p>您可以使用以下命令查看它:</p> <pre><code>var="I am a test string" echo `echo "$var"` # output: I am a test string echo $(echo "$var") # output: $var

编辑:正如 Ed Morton 评论的那样,您不应以这种方式从 shell 传递 awk 变量,而应使用 awk 的 -v 开关:

VARIABLE=$(repquota $FULL_HOME | awk -v min="$MIN" -v max="$MAX" '{if( > min &&  < max )print}')

您的 bash 语法有问题。您没有引用变量,没有错误地引用 awk 脚本,也没有使用不推荐使用的反引号。您似乎想做的是:

VARIABLE=$(repquota "$FULL_HOME" | awk -v min="$MIN" -v max="$MAX" '(>min) && (<max)')

但是由于您没有提供任何示例输入和预期输出,所以这是一个未经检验的猜测,并且总是很难通过阅读不符合您要求的脚本来判断您想要什么。