1

I want to filter on the first field equal to the value of VAR. There is a similar problem here, whose ~ solution (SOL1) I have not been able to reproduce. However, that based on eval (SOL2) works, but seems contrived. I'm looking for a solution that is more like SOL1.

$ cat tmp
a   b   c
d   e   f
g   h   i
$ awk '$1 ~ /d/' tmp
d   e   f
$ VAR='d'

SOL1 (FAIL)

$ awk '$1~VAR' tmp
a   b   c
d   e   f
g   h   i

SOL2 (WORKAROUND)

$ CMD='awk '"'"'$1'"~/$VAR/'"
$ echo "$CMD"
awk '$1~/d/'
$ eval "$CMD" tmp
d   e   f
3

Compare strings with ==.

VAR="d"
awk -v var="$VAR" '$1==var' file

Output:

d   e   f

From man awk:

-v var=val: Assign the value val to the variable var, before execution of the program begins. Such variable values are available to the BEGIN rule of an AWK program.

| improve this answer | |
-2
Done by 2 methods

method1:

var="d"
sed -n '/'$var'/p' file

output

d   e   f

Python

#!/usr/bin/python
import re
var="d"
k=open('ooo','r')
for i in k:
    if var in i:
        print i.strip()

output

d   e   f
| improve this answer | |
  • A risk here is when $var contains anything in $IFS (or contains a forward slash) – Jeff Schaller Aug 2 at 21:04
  • Both solutions fail to restrict the matches to the first field, as required. – Jeff Schaller Aug 2 at 21:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.