You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala Shell脚本中命令引号使用问题求助

Fixing the Sed Command Error in Scala Sys.Process

Hey there! I’ve run into this exact quote-escaping headache with Scala’s sys.process before—let’s break down why your command is failing and how to fix it.

The Root Problem

When you run a command like "sed -i '5a some text' to.file".! in Scala, the sys.process library doesn’t pass the string through a shell by default. Instead, it splits the string into arguments literally. That means sed ends up receiving '5a as the first part of its expression (including the single quote), which is why you get the unknown command: ' error—sed doesn’t recognize the single quote as valid syntax.

Working Solutions

1. Use a Seq for Explicit Arguments (Recommended)

This is the cleanest and most reliable approach. By passing each part of the command as a separate element in a Seq, you avoid all quote-escaping headaches because Scala sends each argument directly to sed without shell interference:

import sys.process._
Seq("sed", "-i", "5a some text", "to.file").!

Here, 5a some text is treated as a single, unquoted argument—exactly what sed expects.

2. Force Shell Interpretation with bash -c

If you need to use shell-specific syntax (like wildcards or variable expansion), you can wrap your command in bash -c to let the shell parse it properly. Just make sure to handle quotes correctly:

// Using triple quotes to avoid escaping
import sys.process._
"""bash -c 'sed -i "5a some text" to.file'""".!

// Or with escaped quotes in a regular string
"bash -c 'sed -i \"5a some text\" to.file'".!

This tells Scala to run bash, which then parses your sed command just like it would in a regular terminal.

Why Your Previous Attempts Failed

  • """sed -i "5a adding some text to" file.text""".!: This splits into arguments like sed, -i, "5a, adding, etc.—the double quotes become part of the argument, which sed rejects.
  • "sed -i \'5a adding some text to\' file.text".!: The escaped single quotes are still treated as literal characters in the argument list, so sed sees '5a instead of 5a.

By using Seq or explicitly invoking the shell, you bypass these parsing issues entirely.

内容的提问来源于stack exchange,提问作者user3467471

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:24:05