18 January 2013

BASH: Single-Quotes inside a Single-Quoted String

In bash, to escape some characters for the command-line arguments properly, you can use single quotes. E.g.,
$ file 'Some # Weird File Name.odt'
But how about the single quote characters? There are several methods. I found the following ways most convenient.

(1) Replace ' with '\''

Break out of the quoted string, and escape the single quote alone.
 $ file 'My wife'\''s file.txt'
(2) Replace ' with '"'"'

Same idea, but different way of escaping the single quote.
$ file 'My wife'"'"'s file.txt'
So, in Python, you can use:
s = string.replace("'", "'\"'\"'")
or in PHP,
s = str_replace("'", "'\"'\"'", string);

No comments:

Post a Comment