Ken J
Ken J

Reputation: 937

Python 3 Escaping Quotes in System Calls

I'm trying to convert new lines in a text file to "\n" characters in a string by running an Awk command using os.system:

awk '{printf "%s\\n", $0}' /tmp/file

My problem is that escaping the quotes is not working:

$ replace = "awk '{printf \"%s\\n\", $0}' /tmp/file"
$ print(replace)
awk '{printf "%s\n", $0}' /tmp/file

I've tried using shlex as well:

$ import shlex
$ line = "awk '{printf \"%s\\n\", $0}'"
$ lexer = shlex.shlex(line, posix=True)
$ lexer.escapedquotes = "'\""
$ mystring = ','.join(lexer)
$ print(mystring)
awk,{printf "%s\n", $0}

I either need to know how to run this awk command with Python or how to convert carriage returns/new lines in a file to "\n" in a string.

EDIT: Here's an example file:

oneline
twoline

threeline

A method should return the following from this file:

oneline\ntwoline\n\nthreeline

Upvotes: 3

Views: 111

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140186

in that case you can use raw prefix + triple quoting:

s = r"""awk '{printf "%s\\n", $0}' /tmp/file"""
print(s)

result:

awk '{printf "%s\\n", $0}' /tmp/file

So os.system(s) works.

in pure python, replace newline by literal \n (adapted from another answer of mine):

with open(file1,"rb") as f:
   contents = f.read().replace(b"\n",b"\\n")
with open(file1+".bak","wb") as f:
   f.write(contents)
os.remove(file1)
os.rename(file1+".bak",file1)

Upvotes: 2

Related Questions