Linux

如何在一組值進入 bash 腳本之前添加換行符?

  • August 20, 2012

我有一組數據管道進入 bash 腳本。以下是該數據的範例:

"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,

我想在“foo1”之前添加一個換行符(\n)。換句話說,將數據更改為讀取:

   \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,

我認為可以使用 sed/awk,但我不太確定 foo1 的值可以/將會改變。

有任何想法嗎?

這將為以“foo”開頭的每一行添加一個’\n’:

sed 's/^"foo1":/\n&/'

awk解決方案:

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

既然你說:

我想在 “foo1” 之前添加一個換行符 (\n)

所以我轉義了反斜杠以插入一個\n字元而不是一個新行。

引用自:https://serverfault.com/questions/419094