How to literally match the Curly braces in python regular expressions

Viewed 31

I need to filter an ip address from a file stored at a remote server. As per the guidence received in the thread , How to filter the first Ip from a 5 tuple that is present in every line in Linux , i was able to filter the IP address on the remote server using the below regex match.

cat <file name> | grep '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}' | awk '{print $4}'

Now i try to pass on the same command to a python script and thats where i;m getting the following error.

    Traceback (most recent call last):
  File "get_flow_diff.py", line 410, in <module>
    getSIPsFromFile(log, vsx_pri_hdl, 'primary')
  File "get_flow_diff.py", line 269, in getSIPsFromFile
    cmd = 'cat {0} | grep \'[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\' | awk \'{print $4}'.format(file_name)
KeyError: '1,3\\'

looks like python is interpreting as a dict since it has curly braces.I tried to precede with backslash but looks like this does not help.

could someone help me to solve this problem

I tried to google it but could not find a working solution.

Thanks.

1 Answers

I wanted to comment but less rep :|, anyways try using triple quotes or double quotes as your command prompt script.

For example:

cmd = '''cat {0} | grep \'[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\' | awk \'{print $4}'''

cmd = "cat {0} | grep \'[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\' | awk \'{print $4}"

Hopefully this works

Related