Perl script runs in terminal but doesn't run when invoked from Java program

前端 未结 1 1403
滥情空心
滥情空心 2020-12-20 20:07

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 co

相关标签:
1条回答
  • 2020-12-20 20:33

    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
    0 讨论(0)
提交回复
热议问题