【问题标题】:Using Quotes with Commands in Scala Shell Scripting在 Scala Shell 脚本中使用带命令的引号
【发布时间】:2018-01-16 09:20:44
【问题描述】:

尝试在 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 上询问。他们建议在这里问。

【问题讨论】:

    标签: linux bash scala shell command-line


    【解决方案1】:

    ' 字符的解释由 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.!
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-29
      • 1970-01-01
      • 2011-03-26
      • 2014-08-06
      • 2010-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多