Reputation: 518
I've spent hours trying to figure this out. I am using shell_exec
(yes, I know the security problems associated with this) and sed to change text in a file.
The problem is no matter what I try I can't seem to output the text with the quotes still intact. I've tried almost every combination of single and double quotes I could to escape it, but it hasn't worked. After hours of trying, I decided to ask the question here.
The code is in a PHP file:
shell_exec('sed -i "s/patterntoreplace/yolo(word,"Hello Everyone", word)/" test.txt
The problem is that the file ends up with:
yolo(word,Hello Everyone, word)
The quotes keep getting parsed and I absolutely need them. I tried various things such as putting it into a variable, using escapeshellarg
and escapeshellcmd
and trying various combinations of single and double quotes, but I still can't get it to work.
This is very frustrating for me because this is the last part of my project and it should be simple, yet I can't run my program without the quotes. It's rather infuriating.
Can someone please tell me what to replace in that command to get quotes to output correctly?
Upvotes: 4
Views: 4469
Reputation: 4534
You can use slashes to use the quotes again inside, but keeping the internal quotes in mind only, in your case: main quote is single
// have added slashes to Hello Everyone
shell_exec('sed -i "s/patterntoreplace/yolo(word,\"Hello Everyone\", word)" test.txt')
Upvotes: 1
Reputation: 158160
This can and should be done with PHP, no sed
required:
$filename = 'test.txt';
$pattern = 'patterntoreplace';
$replace = 'yolo(word,"Hello Everyone", word)';
$lines = [];
foreach(file($filename) as $line) {
$lines []= preg_replace($pattern, $replace, $line);
}
file_put_contents($filename, join("", $lines));
Upvotes: 1
Reputation: 655619
This should work:
$arg = 's/patterntoreplace/yolo(word,"Hello Everyone", word)/';
$cmd = 'sed -i '.escapeshellarg($arg).' test.txt';
shell_exec($cmd);
Upvotes: 2
Reputation: 31
have you tried to use \'
instead of '
and \"
instead of "
where you dont wnat them to be parsed? They said that already! :)
Upvotes: 0