groovy sed错误sed:-e表达式#1,字符1:未知命令:`'';

groovy sed错误sed:-e表达式#1,字符1:未知命令:`'';,groovy,sed,Groovy,Sed,Groovy代码是: def cmd = "sed -i \'1 i <?xml version=\"1.1\"?>\' test.xml" println cmd println cmd.execute().err.text 更新说明: 要检查和更新xml文件 def insertversion(String filename) { def lines= new File (filename).readLines() if(!(lines.get(0)).cont

Groovy代码是:

def cmd = "sed -i \'1 i <?xml version=\"1.1\"?>\' test.xml"
println cmd
println cmd.execute().err.text
更新说明:

要检查和更新xml文件

def insertversion(String filename)
{
    def lines= new File (filename).readLines()
    if(!(lines.get(0)).contains('xml version'))
    {
        def cmd = ['sed', '-i', '1 i <?xml version="1.1"?>', filename]
        cmd.execute()
    }
}
def insertversion(字符串文件名)
{
def lines=新文件(文件名).readLines()
如果(!(lines.get(0)).contains('xml版本'))
{
def cmd=['sed','-i',1i',文件名]
cmd.execute()
}
}

在这种情况下,以cmd和参数列表的形式执行shell命令,而不是以字符串的形式执行命令:

def cmd = ['sed', '-i', '1 i <?xml version="1.1"?>', 'test.xml']
println cmd
println cmd.execute().err.text
它输出:

sed
-i
'1
i
<?xml
version="1.1"?>'
test.xml
sed
-我
'1
我
'
test.xml
您还可以通过在
java.lang.Runtime
类的第96行中设置检查点来运行调试器来验证它:

这当然是错误的。使用列表执行shell命令时,我们将获得正确的命令行参数数组:


一般的经验法则是,如果您的shell命令包含可能会混淆
java.util.StringTokenizer
的字符,最好使用列表来定义正确的命令行参数列表。

@Uchiha_Itachi在脚本中添加了对这两种情况的解释。希望对你有所帮助:)博学了。。谢谢你的解释:)真的很有帮助。我的经验法则是:永远不要使用字符串版本
def cmd = ['sed', '-i', '1 i <?xml version="1.1"?>', 'test.xml']
println cmd
println cmd.execute().err.text
def cmd = "sed -i \'1 i <?xml version=\"1.1\"?>\' test.xml"

def tokenizer = new StringTokenizer(cmd)
def tokens = []
while (tokenizer.hasMoreTokens()) {
    tokens << tokenizer.nextToken()
}

tokens.each { println it }
sed
-i
'1
i
<?xml
version="1.1"?>'
test.xml