Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Awk not working in bash script when use variable in comparison

Tags:

linux

bash

shell

Following is my bash script. If I use varible oid to compare in awk, it doesnt show matching line.

oid="3586302804992"
SYMBOL_CSV_FILE="symbol/BAC"
awk -F, '$5 == $oid' "$SYMBOL_CSV_FILE"
echo "2nd"
awk -F, '$5 == "3586302804992"' "$SYMBOL_CSV_FILE"

O/P is

2nd
BAC,1,O,1,3586302804992

symbol/BAK file contents are

BAC,1,O,1,3586302804992o

Putting "" around $oid , on 3rd line, doesnt make any difference.

like image 209
rahul.deshmukhpatil Avatar asked Sep 25 '26 20:09

rahul.deshmukhpatil


2 Answers

Instead of:

awk -F, '$5 == $oid' "$SYMBOL_CSV_FILE"

use it like this:

awk -F "," -v oid="$oid" '$5 == oid' "$SYMBOL_CSV_FILE"
like image 143
anubhava Avatar answered Sep 27 '26 08:09

anubhava


For bash to interpret your variables, you have to use the double quotes. Single quotes will send $oid as is to your program.

Then, as the $5 will also be interpreted, and you don't want to! You have to escape the $.

In the end, you have:

awk -F, "\$5 == $oid" "$SYMBOL_CSV_FILE"
        ^^          ^
like image 27
Didier Trosset Avatar answered Sep 27 '26 09:09

Didier Trosset



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!