Richa Garg Richa Garg - 2 years ago 57
Bash Question

grep/awk specific lines based on specific fields; using ksh variable with awk

I have this input file: file_in.txt (delimited by pipe)


I want to get only those lines which have 9th field value as
as delimiter so that my output should be:


Below command works fine:

awk -F"|" '{ if ($9 == "}27") print $0 }' file_in.txt

But I want to use a shell variable instead of
for which I tried this:

awk -v tid="$taskid" -F"|" '{ if ($9 == "}tid") print $0 }' file_in.txt

Please help me figure out where I am going wrong with this command.
Any other command suggestions to achieve the same are appreciated.

Answer Source

Assuming your shell variable $tasked has the value 27, you want to use one of these forms:

  1. build the string with the open brace in the shell

    awk -v tid="}$taskid" -F"|" '$9 == tid' file
  2. or do it in awk --- awk's string concatenation is just placing strings side-by-side with optional whitespace in between

    awk -v tid="$taskid" -F"|" '$9 == "}" tid' file
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download