I was running a Perl script that replaces a string with another:
perl -pi.back -e 's/str1/str2/g;' path/to/file1.txt
When I run this command from terminal it well replaces all the occurrences of str1
in the given file to str2
. When I run this from java it does access the file but no replacement occurs:
Runtime.getRuntime().exec("perl -pi.back -e 's/str1/str2/g;' path/to/file1.txt");
ProcessBuilder
class but the same result happens.Runtime.exec()
or ProcessBuilder
with other commands (like gedit newFile.txt
) they work well./usr/bin/perl
instead of perl
in the cmd to ensure the perl cmd is executed.So what do you think the problem is?
EDIT:
I solved this problem by just removing the quotes from the command in java. Thanks to @ikegami for help. So the working version is:
perl -pi.back -e s/str1/str2/g; path/to/file1.txt
instead of
perl -pi.back -e 's/str1/str2/g;' path/to/file1.txt
exec
uses StringTokenizer
to parse the command, which apparently just splits on whitespace.
Take for example the following shell command (similar but different than yours):
perl -pi.back -e 's/a/b/g; s/c/d/g;' path/to/file1.txt
For it, StringTokenizer
produces the following command and arguments:
perl
(command)-pi.back
-e
's/a/b/g;
s/c/d/g;'
path/to/file1.txt
That's completely wrong. The command and arguments should be
perl
(command)-pi.back
-e
s/a/b/g; s/c/d/g;
(Note the lack of quotes.)path/to/file1.txt
You could pass those above to exec(String[] cmdarray)
. Or if you don't have the option of parsing the command, you could actually invoke a shell to parse it for you by passing the following to exec(String[] cmdarray)
:
sh
(command)-c
perl -pi.back -e 's/a/b/g; s/c/d/g;' path/to/file1.txt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With