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,
seduses/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
sedcommand flag (in this case, atcharacter 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 causesedto 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 (soseddoesn't misinterpret them) and ampersands (whichsedtreats 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
相关产品推荐
相关产品推荐

