我将一组数据导入到 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 的值是否可以/将会改变。
有任何想法吗?
答案1
这将为以“foo”开头的每一行添加一个“\n”:
sed 's/^"foo1":/\n&/'
答案2
awk
解决方案:
$ awk '{ sub(/^"foo1"/, "\\n&") }; 1'
$ awk '{ if (/^"foo1"/) { print "\\n" $0 } else { print $0 } }'
既然你说过:
我想在“foo1”前面添加换行符(\n)
因此我转义了反斜杠来插入一个\n
字符而不是一个新行。