[英]sed to add new line after character
Is there away to add new line after matching certain characters in string using sed command?使用 sed 命令匹配字符串中的某些字符后是否可以添加新行? Here is my input string {"foo" = "foovalue","bar" = "barvalue"} Need output like this:
这是我的输入字符串 {"foo" = "foovalue","bar" = "barvalue"} 需要 output 像这样:
{
"foo" = "foovalue",
"bar" = "barvalue"
}
Tried with this but no luck.试过这个,但没有运气。 sed 's/{},/\n' test.txt
sed 's/{},/\n' test.txt
You can get a bit closer to the expected output with您可以更接近预期的 output
sed 's/\([,{]\)/\1\n/g;s/}/\n}/g'
But there's a problem: the indentation doesn't work, and it gets even worse if there are nested objects or arrays (think JSON with =
instead of :
).但是有一个问题:缩进不起作用,如果有嵌套对象或 arrays 会变得更糟(想想 JSON 用
=
而不是:
)。
If there's no nesting, you can just indent any line not starting with a curly brace:如果没有嵌套,您可以缩进任何不以花括号开头的行:
sed 's/\([,{]\)/\1\n/g;s/}/\n}/g;' test.txt | sed '/^[{}]/!s/^/ /'
It can still fail if a comma or a curly brace appears double quoted.如果逗号或花括号出现双引号,它仍然会失败。
A solution without sed
is below.下面是没有
sed
的解决方案。 I am not sure if it works for your general case but for the example you give this just works.我不确定它是否适用于您的一般情况,但对于您给出的示例,它只是有效。
echo '{"foo" = "foovalue","bar" = "barvalue"}' | tr '=' ':' | jq | tr ':' '='
# output:
{
"foo"= "foovalue",
"bar"= "barvalue"
}
You need to install jq
for this.您需要为此安装
jq
。 In ubuntu:在 ubuntu 中:
sudo apt install jq
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.