1

I am new to Python, I have a pipe delimited file and I want to to replace characters enclosed in single quotes with '*' which are present in the last column/4th column.

abc|123|xyz|456|select * from table emp where custname='John'    
xyz|123|'John'|789|select * from table emp   
'John'|456|abc|123|select abc from table emp

In the above example, you can see 'John' in single quote. I want to mask 'John' with '*'. In the second and third rows, you can see 'John' in single quotes, I do not want to mask it because those are not in the last column.

My requirement is to mask data which are in single quotes in the last column.

Expected output:

abc|123|xyz|456|select * from table emp where custname='*'  
xyz|123|'John'|789|select * from table emp  
'John'|456|abc|123|select abc from table emp
Kuldeep Singh Sidhu
  • 3,748
  • 2
  • 12
  • 22
Afz Abd
  • 423
  • 3
  • 19

2 Answers2

0

I hope you find it useful.

# save your text as a variable
text = """abc|123|xyz|456|select * from table emp where custname='John'
xyz|123|'John'|789|select * from table emp
'John'|456|abc|123|select abc from table emp"""

# or if you prefer, save the text in a file (example.txt)
text = open('example.txt','r').read()

import re
name = re.findall("='(.*)'\n",text)[0]
print(text.replace("'"+name+"'\n","'*'\n"))
joaohenry23
  • 145
  • 5
0

enter image description here

The important thing to check is if the last character of the 4th column is a single quote, if yes use string manipulation (whatever you find convenient) to replace the name in single quotes with *, you can find an example down below:

with open('filer.txt') as this_file:                                                
        for line in this_file:
            line = line.strip()
            if line[-1] == "'":
                position = line.rfind("'",0,len(line)-2)
                line = line[:position]+"'*'"
                print(line)
            else:
                print(line)
Mateo Lara
  • 827
  • 2
  • 12
  • 29
  • Why are you using csv reader? You aren't using it to separate the pipes (which would make sense). Why not just iteratre through the lines in `this_file`? – Oddthinking Jun 12 '20 at 06:28
  • Note3 this answer is very sensitive to unmatched quotes, and will fail if the quoted text does not end in the last position of the last field. – Oddthinking Jun 12 '20 at 06:30
  • Thanks, @Oddthinking, CSV is not required we can use this_file directly as you suggest (please see the edited version) also the Note3 is super accurate. – Mateo Lara Jun 12 '20 at 08:23