Search code examples
pythonlinuxshellawksubprocess

Pass File Name dynamically inside awk cmd python


import subprocess
f1 = File_1.csv
f2 = File_2.csv
command_line = "awk -F ',' 'FNR==NR {a{[$1]=$0; next} $1 in a' {} {}".format(f1,f2)
result = subprocess.run(command_line,shell=True,stdout=subprocess.PIPE)
output = result.stdout.decode('utf-8')

Trying to pass the file in dynamic way , but getting key error / file not found error.

Is there any suggestions to pass the filename in dynamic way inside awk cmd in python ?

TIA.


Solution

  • fixing your code, check before How do I escape curly-brace ({})

    import subprocess
    f1 = "File_1.csv"
    f2 = "File_2.csv"
    command_line = "awk -F ',' 'FNR==NR {{a[$1]=$0; next}} $1 in a' {} {}".format(f1,f2)
    result = subprocess.run(command_line,shell=True,stdout=subprocess.PIPE)
    output = result.stdout.decode('utf-8')