簡體   English   中英

轉義sed字符Java不起作用

[英]escaping sed characters java not working

我首先要說的是,我發現了很多與我類似的主題,但是沒有一個能夠為我提供正確的答案。

我正在嘗試使用以下shell腳本將字符串插入xml文件:

#!/bin/bash
cd /var/lib/tomcat7/webapps/Config || exit 
sudo sed -i '/<\/home>/i <entry>'"$@"'</entry>' data.xml

當執行類似./script.sh“ test entry”的腳本時,我的xml文件將如下所示:

<home>
    <entry>test entry</entry>
</home>

這就是我想要的。 但是,當我嘗試通過Java調用此腳本時,無法成功轉義引號。

我的Java代碼是這樣的:

String entry = "test entry";
String command = "/home/user/addentry.sh " + "\"" + entry + "\"";
Process p = null;
Runtime run = Runtime.getRuntime();
    try {            
        p = run.exec(command);
    }     
    .....   

執行代碼后,我的xml文件如下所示:

<home>
    <entry>"test
</home>

如您所見,引號也作為我輸入的一部分傳遞。 將Java代碼更改為:

String command = "/home/user/addentry.sh " + entry;

它對於沒有空格的字符串正常工作(因此腳本只有1個參數)

提前致謝

嘗試這個:

package org.script.test;

import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        if (args.length != 1) {
            System.out.println("Invalid arguments");
            return;
        }
        String entry="\"" +args[0]+ "\"";
        System.out.println("adding: " + entry);

        Process pr = null;
        try {
            pr =
 Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", "cd /home/oracle/testscript ; . ./test.sh " + entry });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

致電者:

假設包org.script.test

java -Xms128M -Xmx128M -classpath testScript.jar org.script.test.Main "test entry"

即使您不傳遞參數也可以使用:

package org.mihai.script;

import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        String entry = "test entry 2";
        System.out.println("adding: " + entry);

        Process pr = null;
        try {
            pr =
 Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", "cd /home/oracle/testscript ; . ./test.sh " + "\"" + entry +"\"" });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

呼叫:

java -Xms128M -Xmx128M -classpath testScript.jar org.mihai.script.Main

輸出data.xml:

<home>
<entry>test entry</entry>
<entry>test entry 2</entry>
</home>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM