In Python, we can do something like this:
pattern = "foo"
searchfile = "/root/text"
search = "bar"
replace = "baz"
tempfile = tempfile.mkstemp()[1]
grepcmd = ["/bin/grep", "-E", pattern, searchfile]
sedcmd = ["/bin/sed", "-E", "s/{0}/{1}/g".format(search, replace)]
with open(tempfile, "w") as temphandle:
grep = subprocess.Popen(grepcmd, stdout=subprocess.PIPE)
sed = subprocess.Popen(sedcmd, stdin=grep.stdout, stdout=temphandle)
grep.stdout.close()
sed.communicate()
You can see that the stdout
from the grep
command is passed as stdin
to the sed
command, which in turn specifies a file handle as its stdout
. This is equivalent to this shell command:
grep -E foo /root/text | sed -E 's/bar/baz/g' > /tmp/whatever
I'd like to replicate this behaviour in PHP, but am not finding the equivalent native functionality. What I've been doing is to build the equivalent shell command as a long string and pass it to shell_exec()
but this is messy, especially with correct use of escapeshellarg()
(note escaping is not required in the above Python code.)
$pattern = "foo";
$searchfile = "/root/text";
$search = "bar";
$replace = "baz";
$tempfile = tempnam(sys_get_temp_dir(), 'asdf');
$grepcmd = "/bin/grep -E " . escapeshellarg($pattern) . " " . escapeshellarg($searchfile);
$sedcmd = "/bin/sed -E " . escapeshellarg("s/$search/$replace/g");
exec("$grepcmd | $sedcmd > $tempfile);
I can also run each command separately, capturing the output in a variable, and passing it to the next command but this has obvious inefficiencies.
Is there any native way to do something similar in PHP or is my current method as good as it's going to get?