2

I've got a set of data piping into a bash script. Here's an example of what that data looks like:

"foo1": "Miscellaneous text",
    "foo2": "More text",
    "foo3": "blah blah blah",
      "foo4": 1635.0,
      "foo5": 0.0,
"foo1": "Miscellaneous text that is different",
    "foo2": "More text1231231",
    "foo3": "blah blah blah234234",
      "foo4": 1633425.0,
      "foo5": 0.0,
"foo1": "Miscellaneous text abc123",
    "foo2": "More text122121",
    "foo3": "blah blah blah414124",
      "foo4": 163235.0,
      "foo5": 1.0,
"foo1": "More Miscellaneous text",
    "foo2": "asdfasdfaMore text",
    "foo3": "blah blahadsfasdf blah",
      "foo4": 1635232.0,
      "foo5": 0.0,

I want to add a line break character (\n) to precede "foo1". In other words, change the data to read:

    \n"foo1": "Miscellaneous text",
        "foo2": "More text",
        "foo3": "blah blah blah",
          "foo4": 1635.0,
          "foo5": 0.0,
    \n"foo1": "Miscellaneous text that is different",
        "foo2": "More text1231231",
        "foo3": "blah blah blah234234",
          "foo4": 1633425.0,
          "foo5": 0.0,
    \n"foo1": "Miscellaneous text abc123",
        "foo2": "More text122121",
        "foo3": "blah blah blah414124",
          "foo4": 163235.0,
          "foo5": 1.0,
    \n"foo1": "More Miscellaneous text",
        "foo2": "asdfasdfaMore text",
        "foo3": "blah blahadsfasdf blah",
          "foo4": 1635232.0,
          "foo5": 0.0,

I thought it would be possible to do with sed/awk but I'm not so sure as the values for foo1 can/will change.

Any ideas?

  • So you want to add a line break at the beginning of every line that doesn't start with a space/tab? – scai Aug 19 '12 at 16:10
  • @scai I suppose that would work but I was originally wanting to add a line break at the beginning of every line that begins with "foo1": – Mike B Aug 19 '12 at 16:11
  • 1
    I thought the "foo1": can/will change? If not, it is really easy. See my answer. – scai Aug 19 '12 at 16:29
  • foo1 stays the same. The value for foo1 is what changes. For example, it could be "Miscellaneous text". It could later be "Miscellaneous text that is different" – Mike B Aug 19 '12 at 16:33
1

This will add a '\n' for every line starting with "foo":

sed 's/^"foo1":/\n&/'
  • 1
    There's a typo: "foo" should be "foo1". The best way to prevent such typos: sed 's/^"foo1":/\n&/' – Dennis Williamson Aug 20 '12 at 0:51
1

awk solutions:

$ awk '{ sub(/^"foo1"/, "\\n&") }; 1'
$ awk '{ if (/^"foo1"/) { print "\\n" $0 } else { print $0 } }'

Since you said:

I want to add a line break character (\n) to precede "foo1"

So I escaped the backslash to insert a \n character instead of a new line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.