问题描述
我看过很多关于此的帖子,但无法弄清楚我到底需要什么.我试过 -r
和 argjson
等等.
I've seen a number of posts on this but can't figure out what I need exactly. I've tried -r
and argjson
among other things.
我需要换行符保持为 \n
并且不会被转义为 \\n
.
I need the newlines to remain as \n
and not be escaped to \\n
.
我还希望能够将 ``` 用于代码块,但它会忽略该字符串部分.
I'd also like to be able to use ``` for code blocks but it ignores that section of the string.
FALLBACK_MESSAGE="TEST MESSAGE - $HOSTNAME"
MARKDOWN_MESSAGE="TEST MESSAGE - $HOSTNAME \(0x0a) \(\n) Hi <@U12345789>\n```Can we do a\nmultiline code block```"
JSON_STRING=$( jq -nr \
--arg fallbackMessage "$FALLBACK_MESSAGE" \
--arg sectionType "section" \
--arg markdownType "mrkdwn" \
--arg textMessage "$MARKDOWN_MESSAGE" \
'{
text: $fallbackMessage,
blocks: [
{
type: $sectionType,
text: {
type: $markdownType,
text: $textMessage
}
}
]
}')
echo $JSON_STRING
输出:
{ "text": "TEST MESSAGE - devDebug", "blocks": [ { "type": "section", "text": { "type": "mrkdwn", "text": "TEST MESSAGE - devDebug \\(0x0a) \\(\\n) Hi <@U12345789>\\n" } } ] }
推荐答案
确保您的 shell 变量包含实际换行符,而不是 \n
序列.
Make sure your shell variables contain actual newlines, not \n
sequences.
如果您希望 bash 将字符串中的转义序列转换为它们所指的字符,可以使用 printf %b
来实现此目的.
If you want bash to convert escape sequences in a string into the characters they refer to, printf %b
can be used for this purpose.
#!/usr/bin/env bash
fallback_message="TEST MESSAGE - $HOSTNAME"
markdown_message="TEST MESSAGE - $HOSTNAME \(0x0a) \(\n) Hi <@U12345789>\n\`\`\`Can we do a\nmultiline code block\`\`\`"
# create markdown_message_unescaped with an unescaped version of markdown_message
printf -v markdown_message_unescaped %b "$markdown_message"
jq -n \
--arg textMessage "$markdown_message_unescaped" \
--arg fallbackMessage "$fallback_message" \
--arg sectionType section --arg markdownType markdown '
{
text: $fallbackMessage,
blocks: [
{
type: $sectionType,
text: {
type: $markdownType,
text: $textMessage
}
}
]
}'
...正确地作为输出发出:
...properly emits as output:
{
"text": "TEST MESSAGE - YOUR_HOSTNAME",
"blocks": [
{
"type": "section",
"text": {
"type": "markdown",
"text": "TEST MESSAGE - YOUR_HOSTNAME (0x0a) (\n)\nHi <@U12345789>\n```\nCan we do a multiline code block\n```"
}
}
]
}
这篇关于将换行符与 jq 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!