Shashank Vivek
Shashank Vivek

Reputation: 17514

Why awk -v not working

I have a function in shell:

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 ""
}

In debug mode, I can see the value getting passed on :

+ name=topbeat.yml
++ awk -v file=topbeat.yml '-F|' '{if($1~/file/)print $2}' ps.conf
+ dest=

But I am not getting the value of dest, I want it to be /etc/topbeat/ , where as

  awk -F"|" '{if($1~/topbeat/)print $2}' ps.conf

returns expected O/P i.e /etc/topbeat/

ps.conf

topbeat.yml|/etc/topbeat/
logstash.conf|/opt/monitor/tools/etc/
jmxd.tar|/opt/

Upvotes: 1

Views: 537

Answers (1)

Tom Fenech
Tom Fenech

Reputation: 74705

The syntax /pattern/ can only be used for literals, not with variables.

You need to change:

$1~/file/

to:

$1 ~ file

Note that the structure of an awk script is condition { action }, where condition defaults to 1 (true) and { action } defaults to { print } (print the whole record, $0). As such, you don't need to use if:

$1 ~ file { print $2 }

Also, remember to always quote your variables:

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

With a couple more changes, this would be the final result:

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"
}

Upvotes: 5

Related Questions