0

This is the formatting done for this ubuntu command egrep -v "usernameshere" in python as bellow

userfilter = ["egrep", "-v", "\"{filter}\"".format(filter=filteruser)]

Why doing: I am passing this to a subprocess and executing the command from python.

Now I want to accomplish the same for this command how to do it.

awk '{gsub("admin","");print}'

I tried the below one but not working, some syntax errors

Try 1

userfilter=["awk","\'{gsub({filter},\"\");print}\'".format(filter=filteruser)] 

Try 2

userfilter=["awk","\'{gsub({filter}.format(filter=filteruser),\"\");print}\'"]

Errors:

TRY 1 Error:

userfilter=["awk","\'{gsub({filter},\"\");print}\'".format(f‌​ilter=filteruser)] KeyError: 'gsub({filter},"");print'

TRY 2 Error:

awk: 1: unexpected character '.'
awk: line 1: extra ')'
Tara Prasad Gurung
  • 3,422
  • 6
  • 38
  • 76
  • What is the specific syntax error that you've encountered? – Eduard May 22 '17 at 07:23
  • `userfilter=["awk","\'{gsub({filter},\"\");print}\'".format(filter=filteruser)] KeyError: 'gsub({filter},"");print'` in first Case – Tara Prasad Gurung May 22 '17 at 07:24
  • I suppose your having issues with the usage of multiple curly brackets. Try this instead `userfilter=["awk","\'{gsub("+filteruser+",\"\");print}\'"]` – Eduard May 22 '17 at 07:33
  • Here's a great answer to your question http://stackoverflow.com/questions/5466451/how-can-i-print-literal-curly-brace-characters-in-python-string-and-also-use-fo – Eduard May 22 '17 at 07:36

1 Answers1

0

So basically the usage of multiple curly brackets is giving you syntax issue. Simply use double curly brackets to print actual curly brackets in your string.

userfilter=["awk","\'{{gsub({filter},\"\");print}}\'".format(filter=filteruser)]

Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.

Related question

I'm not sure how your encountering the second error, because when I copy paste this to my terminal, I get no error, but simply a string literal.

>>> userfilter=["awk","\'{gsub({filter}.format(filter=filteruser),\"\");print}\'"]
>>> userfilter
['awk', '\'{gsub({filter}.format(filter=filteruser),"");print}\'']
Community
  • 1
  • 1
Eduard
  • 666
  • 1
  • 8
  • 25
  • The error comes when i use that in subprocess and run it ,Its obviously not going to run if we simply check the variable – Tara Prasad Gurung May 22 '17 at 07:42
  • As the document states, simply use double curly brackets if you want include a brace character in the literal text. . `userfilter=["awk","\'{{gsub({filter}.format(filter=filteruser),\"\");print}}\'"]` – Eduard May 22 '17 at 07:45
  • that didn't work `awk: 1: unexpected character ''' awk: line 1: syntax error at or near |` – Tara Prasad Gurung May 22 '17 at 07:52