Home > Software engineering >  sed to add new line after character
sed to add new line after character

Time:08-25

Is there away to add new line after matching certain characters in string using sed command? Here is my input string {"foo" = "foovalue","bar" = "barvalue"} Need output like this:

{
  "foo" = "foovalue",
  "bar" = "barvalue"
}

Tried with this but no luck. sed 's/{},/\n' test.txt

CodePudding user response:

A solution without sed is below. 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. In ubuntu:

sudo apt install jq

CodePudding user response:

You can get a bit closer to the expected output with

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 :).

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.

  • Related