awk a string

Hi

#!/usr/bin/bash
ITEM=apple
cat file1.tsv | awk -F "\t" '($3 == $ITEM) {print $2}'

awk: illegal field $(), name "ITEM"
 input record number 1, file
 source line number 1

Here is file1.tsv

type category_id item code remarks
fruits 1 apple 345 567
fruits 3 banana 44 555

:confused:

Use the -v option for shell variables, read your awk documentation.

Regards

awk -v ITEM=$ITEM '($3 == ITEM) {print $2}' file1.csv

your single quotes mask the $, ond so the shell can't substitute this variable

:b: Thanks a lot

But What about the delimiter?

awk -F '\t' '$3 == ITEM { print $2 }' ITEM=apple infile

this will also work i guess....

awk -F"\t" '$3 == '$ITEM'{print $2}' filename

Hm, did you try it?

I wanna use predefined variable.

---------- Post updated at 06:30 PM ---------- Previous update was at 06:29 PM ----------

resulted null ??

awk -F '\t' '$3 == ITEM { print $2 }' ITEM="$ITEM" infile

If you need the value of ITEM available in the BEGIN block use the already mentioned -v syntax.