Richa Garg Richa Garg - 7 months ago 7
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)

3345:tyg|rty|27|0|0|ty6|{89|io|}62|0
3346:tyg|rtyuio|63|0|1|ty6|{89|gh|}45|0
3347:tyu|ray|24|0|0|ty6|{89|uh|}27|0
3348:tyg|rtoy|93|0|1|ty6|{89|yh|}1|0
3349:tyo|rtert|28|0|0|ty6|{89|gh|}27|0


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

3347:tyu|ray|24|0|0|ty6|{89|uh|}27|0
3349:tyo|rtert|28|0|0|ty6|{89|gh|}27|0


Below command works fine:

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


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

taskid="}27"
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

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
    
Comments