Passing variable values to awk command in python scripting

I am having below awk command

awk -F "|" '{ if($132==0 && $123==1) print $145}' abc.dat

I want to generate awk command by passing values from below variables a,b,c as substitutes instead of numerical values and execute it but it is not happening. It is giving me syntax error. can someone help me in running this awk command using python scripting?

a = 132,

b = 123,

c = 145

I am using python 3.4.4

Upvotes: 0

Views: 291

Answers (1)

Amitai Irron
Amitai Irron

Reputation: 2055

You want to pass the column numbers you test and print to awk from some Python code. You would need to do something like this:

import subprocess

def awk_by_cols(a, b, c):
    program = "{ if($%d==0 && $%d==1) print $%d}" % (a, b, c)
    return subprocess.check_output(["awk", "-F|", program, "abc.dat"])

if __name__ == "__main__":
    print(awk_by_cols(1, 2, 4).decode())

# Sample data file abc.dat holds:
"""\
0|0|0|0
0|0|1|1
0|1|0|2
0|1|1|3
1|0|0|4
1|0|1|5
1|1|0|6
1|1|1|7
"""

Embedding the column numbers in the program string can be done using many other methods. I chose the most traditional method - printf-style.

Upvotes: 1

Related Questions