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
相关产品推荐
相关产品推荐

