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

Bash中使用sed -i替换含$变量的整行失败求助

问题描述

需要用Bash的sed -i命令替换insert.sh指定行内容,其中替换字符串包含带路径的变量,除第5、6行外其余替换正常,执行时出现sed错误:

sed: -e expression #1, char 27: unknown option to `s'
sed: -e expression #1, char 26: unknown option to `s'

相关文件内容:

write.sh

#!/bin/bash

output_file="/random/path/that/should/be/there1/"
error_file="/random/path/that/should/be/there2/"

sed -i '2s/.*/#SBATCH --job-name=775_none/' insert.sh
sed -i '3s/.*/#SBATCH --cpus-per-task=1/' insert.sh
sed -i '4s/.*/#SBATCH --mem=5GB/' insert.sh
sed -i '5s/.*/#SBATCH --output="'$output_file'"/' insert.sh
sed -i '6s/.*/#SBATCH --error="'$error_file'"/' insert.sh
sed -i '7s/.*/#SBATCH --time=5:00:00/' insert.sh

原insert.sh

#!/bin/bash
#SBATCH --job-name=none-chi-1
#SBATCH --cpus-per-task=1
#SBATCH --mem=5GB
#SBATCH --output=/path/i/want/to/repalce
#SBATCH --error=/path/i/want/to/repalce
#SBATCH --time=8:00:00

期望的insert.sh

#!/bin/bash
#SBATCH --job-name=775_none
#SBATCH --cpus-per-task=1
#SBATCH --mem=5GB
#SBATCH --output=/random/path/that/should/be/there1/
#SBATCH --error=/random/path/that/should/be/there2/
#SBATCH --time=5:00:00
错误原因

sed的s命令默认使用/作为分隔符,而output_file和error_file变量中的路径包含大量/,导致sed误将路径中的/识别为命令分隔符,从而抛出语法错误。

解决方案

有两种可行的解决方式:

方法1:更换sed的分隔符

选择一个变量内容中不存在的字符作为分隔符,比如|或@,修改第5、6行的sed命令:

sed -i '5s|.*|#SBATCH --output="'$output_file'"|' insert.sh
sed -i '6s|.*|#SBATCH --error="'$error_file'"|' insert.sh

方法2:转义变量中的/

将变量里的/转义为\/,避免被sed误解析:

escaped_output=$(printf '%s' "$output_file" | sed 's/\//\\\//g')
escaped_error=$(printf '%s' "$error_file" | sed 's/\//\\\//g')
sed -i '5s/.*/#SBATCH --output="'$escaped_output'"/' insert.sh
sed -i '6s/.*/#SBATCH --error="'$escaped_error'"/' insert.sh

修改后的完整write.sh示例(推荐方法1,更简洁):

#!/bin/bash

output_file="/random/path/that/should/be/there1/"
error_file="/random/path/that/should/be/there2/"

sed -i '2s/.*/#SBATCH --job-name=775_none/' insert.sh
sed -i '3s/.*/#SBATCH --cpus-per-task=1/' insert.sh
sed -i '4s/.*/#SBATCH --mem=5GB/' insert.sh
sed -i '5s|.*|#SBATCH --output="'$output_file'"|' insert.sh
sed -i '6s|.*|#SBATCH --error="'$error_file'"|' insert.sh
sed -i '7s/.*/#SBATCH --time=5:00:00/' insert.sh

内容的提问来源于stack exchange,提问作者B.Eng

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 21:45:37