3

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.

1
  • 1
    To use bash variables inside an awk script, you need to "pass" them with -v. For example num=3; awk -v n=$num 'BEGIN{print n}'. Commented Aug 13, 2013 at 11:50

2 Answers 2

6

Instead of:

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

use it like this:

awk -F "," -v oid="$oid" '$5 == oid' "$SYMBOL_CSV_FILE"
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, Worked in right way. @Anubhava: the variable passing mechanism to awk has any specific reason?
Yes -v is standard way to pass variables from shell to awk. These variable then become standard awk variables and you can use them without quoting or $ inside awk scripts.
1

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

2 Comments

Giving error as awk: == 3586302804992 awk: ^ syntax error 2nd BAC,1,O,1,3586302804992
@rahul.deshmukhpatil Fixed with escaping the $5. Thanks for pointing this out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.