1
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.

  • 1
    Does this answer your question? [How do I escape curly-brace ({}) characters in a string while using .format (or an f-string)?](https://stackoverflow.com/questions/5466451/how-do-i-escape-curly-brace-characters-in-a-string-while-using-format-or) – Friedrich Mar 20 '23 at 11:39
  • No , I have to pass f1,f2 dynamically. Just I tried with formatting but no luck. – prasannakpechu Mar 20 '23 at 11:52
  • 2
    I suspect the curly braces around `{a{[$1]=$0; next}` break things. You would need to put double curly braces like this: `{{a{{[$1]=$0; next}}`. Also, isn't there a closing brace missing? If that doesn't fix it, please edit your question and share the exact error message you get. – Friedrich Mar 20 '23 at 11:57
  • 4
    Aside from the (correct) comments by Friedrich: Why do you involve the shell here? Wouldn't it be easier (and less error-prone) to bypass the shell, and call `awk` directly from Python? Having said this: Why are you using awk at all? You could do everything easily within Python. – user1934428 Mar 20 '23 at 12:10
  • Thanks for the info @user1934428 , I am supposed to use awk. – prasannakpechu Mar 21 '23 at 07:29

1 Answers1

0

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')
Jose Ricardo Bustos M.
  • 8,016
  • 6
  • 40
  • 62