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

sed命令在命令行正常运行,脚本执行报unknown option to `s'错如何解决?

问题解决思路

核心原因

你遇到的sed报错,本质是shell脚本中对单引号的解析规则和终端直接执行时的差异。原命令里用了's,http://localhost:8080,'',g',终端bash中连续两个单引号会被解析为空字符串,但在脚本(尤其是用sh执行时),单引号内部无法嵌套单引号,导致sed的替换表达式被错误解析,触发"unknown option"错误。

修复方案

有两种简单的修正方式:

方式1:简化替换表达式(推荐)

既然目标是把http://localhost:8080替换为空字符串,直接省略中间的空引号,用连续两个逗号即可:

find . -type f -name "*.service.ts" -print0 | xargs -0 sed -i 's,http://localhost:8080,,g'

方式2:调整引号包裹方式

如果要保留空字符串的写法,可以改用双引号包裹sed表达式(这里无变量,不会触发shell解析问题):

find . -type f -name "*.service.ts" -print0 | xargs -0 sed -i "s,http://localhost:8080,,g"

额外注意:脚本的shebang

确保脚本开头加上#!/bin/bash,强制用bash执行,避免Ubuntu默认sh指向的dash带来的语法差异:

#!/bin/bash
find . -type f -name "*.service.ts" -print0 | xargs -0 sed -i 's,http://localhost:8080,,g'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 13:45:27