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

Shell脚本替换JSON中字符串为证书内容时sed报错问题

Fixing the sed: bad flag in substitute command Error When Injecting Certificates into JSON

Let's break down what's causing this error and how to fix it properly:

Why the Error Happens

The error sed: 1: "s/ORDERER_CA_CERT/----- ...": bad flag in substitute command: 't' occurs because:

  • By default, sed uses / as the delimiter for its substitute command (s/search/replace/flags).
  • Your certificate content likely contains characters that interfere with this delimiter, or gets misinterpreted as a sed command flag (in this case, a t character in your cert text was being treated as a jump flag instead of part of the certificate).
  • Additionally, unescaped special characters like & or backslashes in the certificate will cause sed to misprocess the substitution.

Step-by-Step Solution

1. Properly Process the Certificate Content

First, convert the multi-line certificate into a JSON-compatible single line, and escape characters that would break sed:

# Read the cert, convert newlines to JSON-friendly \\n, escape backslashes and & for sed
CERT=$(cat cert.crt | awk '{printf "%s\\n", $0}' | sed 's/\\/\\\\/g; s/&/\\&/g')
  • awk '{printf "%s\\n", $0}': Appends an escaped newline (\\n) to each line of the cert, making it valid for JSON string values.
  • sed 's/\\/\\\\/g; s/&/\\&/g': Escapes backslashes (so sed doesn't misinterpret them) and ampersands (which sed treats as a reference to the matched search string).

2. Use a Non-Conflicting Delimiter in sed

Instead of the default / delimiter, pick a character that won't appear in your certificate (like # or |):

# Replace _CERT_ in the template with the processed cert, output to test.json
sed "s#_CERT_#$CERT#g" template.json > test.json

Using # as the delimiter avoids conflicts with any / characters that might be present in your certificate (uncommon, but possible in some PEM formats).

Verify the Result

Open test.json and check that the certificate content is a valid JSON string:

  • It should be enclosed in double quotes.
  • Newlines from the original cert are represented as \n.
  • No stray characters that would break JSON parsing.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:40:57