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

Bash中sed命令报错:未终止`s`命令的问题求解

问题分析与修复方案

直接报错原因

你遇到的sed: -e expression #1, char 19: unterminated 's' command错误,核心原因是sed替换命令末尾多了一个多余的斜杠:

sed -i "s/$(tput setaf 1)$(printf '%s' $current_day)$(tput sgr0)/$current_day/g/" calendar.txt
# 这里的 `g/` 是错误写法,正确应为 `g`

sed的s命令格式是s/匹配模式/替换内容/标志,额外的尾斜杠会让sed判定命令未完成,从而抛出"未终止的s命令"错误。

其他潜在问题修正

除了上述直接错误,脚本还有两处语法问题需要调整:

  • 变量赋值语法错误:bash中变量赋值不能有空格,current_day = "6" 需改为 current_day="6"
  • 冗余的printf:$(printf '%s' $current_day) 完全可以直接用$current_day替代,简化代码

修复后的完整脚本

#!/bin/bash

current_day="6"
sed_output=$(sed -E "s/\b${current_day}\b/$(tput setaf 1)&$(tput sgr0)/g" "calendar.txt")

if echo "$sed_output" | grep -q "$current_day"; then
   echo "Value '$current_day' found in the modified output."
   sed -i "s/$(tput setaf 1)$current_day$(tput sgr0)/$current_day/g" calendar.txt
   echo "Modifier removed."
else
    echo "Value '$current_day' not found in the modified output."
fi

额外优化建议

如果tput输出的终端控制字符中包含斜杠这类sed的默认分隔符,可改用其他符号(比如#)作为分隔符,避免冲突:

sed -i "s#$(tput setaf 1)$current_day$(tput sgr0)#$current_day#g" calendar.txt

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 17:57:12