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");
- I'm sure it accesses the file (the file seems to be edited in gedit(reload required)).
- I tried Java
ProcessBuilder
class but the same result happens. - When I use
Runtime.exec()
orProcessBuilder
with other commands (likegedit newFile.txt
) they work well. - Ironically, I printed the above perl command from java and take the paste in terminal and the replace operation is done!
- No exceptions or errors by using those commands. (I used try and catch to ensure this).
- I also used
/usr/bin/perl
instead ofperl
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()
returns you aProcess
, it hasgetInputStream()
andgetErrorStream()
methods which return you whatever output the process creates. See what this process outputs. – Transformerecho "foo's"
andecho foo\'s
? None whatsoever. Both passfoo's
toecho
. – Conceivable