为什么awk -v不工作

时间:2016-07-13 08:40:52

标签: shell awk

我在shell中有一个函数:

                     A         B         C         D         E
a 2001-01-31  0.864841  0.789273  0.370031  0.448256  0.178515
  2001-02-28  0.991861  0.079215  0.900788  0.666178  0.693887
  2001-03-31  0.016674  0.855109  0.984115  0.436574  0.480339
b 2001-01-31  0.497646  0.349958  0.223227  0.812331  0.975012
  2001-02-28  0.542572  0.472267  0.276186  0.970909  0.138683
  2001-03-31  0.960813  0.666942  0.069349  0.282741  0.127992

在调试模式下,我可以看到传递的值:

ConfigHandler(){
    name=$1
    dest=`awk -v file=$name -F"|" '{if($1~/file/)print $2}' ps.conf`
    echo $dest
    echo "Moving $1 to $dest ...."
    mv `pwd`/$1 $dest/$1
    echo ""
    echo ""
}

但我没有得到+ name=topbeat.yml ++ awk -v file=topbeat.yml '-F|' '{if($1~/file/)print $2}' ps.conf + dest= 的价值,我希望它是dest,其中

/etc/topbeat/

返回预期的O / P,即 awk -F"|" '{if($1~/topbeat/)print $2}' ps.conf

ps.conf

/etc/topbeat/

1 个答案:

答案 0 :(得分:5)

语法/pattern/只能用于文字,而不能用于变量。

您需要更改:

$1~/file/

为:

$1 ~ file

请注意,awk脚本的结构为condition { action },其中condition默认为1(true),{ action }默认为{ print }(打印整个记录,$0)。因此,您无需使用if

$1 ~ file { print $2 }

另外,请记住始终引用您的变量:

awk -v file="$name" # ...
echo "$dest" # etc.

经过几次更改后,这将是最终结果:

ConfigHandler(){
    dest=$(awk -v file="$1" -F"|" '$1 ~ file { print $2 }' ps.conf)
    printf 'Moving %s to %s...\n\n\n' "$1" "$dest"
    mv "$1" "$dest"
}