bash - 如何在多行中编写单行字符串?
问题描述
我想通过 curl 发送一个带有长字符串字段的大 json,我应该如何将它裁剪为多行?例如:
curl -X POST 'localhost:3000/upload' \
-H 'Content-Type: application/json'
-d "{
\"markdown\": \"# $TITLE\\n\\nsome content with multiple lines....\\n\\nsome content with multiple lines....\\n\\nsome content with multiple lines....\\n\\nsome content with multiple lines....\\n\\n\"
}"
解决方案
您可以使用帖子中已有的技术将任何内容拆分为多行,方法是使用\
. 如果您需要在带引号的字符串中间拆分,请终止引号并开始一个新的。例如,这些是等效的:
echo "foobar"
echo "foo""bar"
echo "foo"\
"bar"
但是对于您的具体示例,我推荐一种更好的方法。在双引号字符串中创建 JSON 非常容易出错,因为必须转义所有内部双引号,这也变得难以阅读和维护。更好的选择是使用 here-document,将其通过管道传输到curl
,并用于-d@-
使其从标准输入读取 JSON。像这样:
formatJson() {
cat << EOF
{
"markdown": "some content with $variable in it"
}
EOF
}
formatJson | curl -X POST 'localhost:3000/upload' \
-H 'Content-Type: application/json'
-d@-
推荐阅读
- javascript - 开玩笑:测试超时后拒绝的承诺
- firebase - 如何增加单张签证卡在firebase中可以覆盖的项目数量
- android - 安装 react-native-onesignal 时无法解决:com.google.android.gms:play-services-ads-identifier:12.0.1
- java - 将两个对象序列化为彼此的字段
- java - Vaadin 将组件颜色设置为 hex 或 int 或 rgb
- groovy - 将字符串转换为列表 [Groovy]
- r - 当存在较短版本时,在 R 中排除字符串中的字符
- sql - Laravel 查询生成器的 SQL 子查询 JOIN 问题
- reactjs - React Table 无法正确显示数据
- html - 被 div 截断的内容