gpt4 book ai didi

linux - 在 Scala Shell 脚本中对命令使用引号

转载 作者:太空狗 更新时间:2023-10-29 11:41:17 24 4
gpt4 key购买 nike

尝试在 scala bash 文件中使用以下命令(已导入 sys.process._):

val writeToLine5 = "sed -i '5a some text' to.file".!

出现以下错误:

> "sed: -e expression #1, char 1: unknown command: `'';

命令本身在命令行中运行完美。

也试过:

"""sed -i "5a adding some text to" file.text""".!;
"sed -i \'5a adding some text to\' file.text".!;

这里有 scala shell 脚本专家吗?谢谢!

PS: 已经在 askubuntu.com 上问过了。他们建议在这里询问。

最佳答案

' 字符的解释由 shell 完成,而不是由 sed 本身完成,因此通常最简单的方法是让 shell 为您完成。

import sys.process._

val writeToLine5 = Seq("sh", "-c", "sed -i '5a some text' to.file").!

但您可以自己进行解释。

val writeToLine5 = Seq("sed", "-i", "5a some text", "to.file").!

您也可以使用 Regex 模式来解释内部引用,但它很容易出错,我真的不推荐它。

val cmd = "sed -i '5a some text' to.file"
val res = cmd.split(""" +(?=([^'"]*['"][^'"]*['"])*[^'"]*$)""") //split on non-quoted spaces
.map(_.replaceAll("['\"]","")) //remove all the internal quote marks
.toSeq.!

关于linux - 在 Scala Shell 脚本中对命令使用引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48277781/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com