Json 如何使用awk/sed在两行之间添加新的文本行?(在文件中)

Json 如何使用awk/sed在两行之间添加新的文本行?(在文件中),json,linux,bash,awk,sed,Json,Linux,Bash,Awk,Sed,我有以下代码块: { "operation_machine": "Ford", "operation_steps": [ "steps/Step_1/01_paint_the_car.json", "steps/Step_2/01_drive_the_car.json", "steps/Step_2/02_park_the_car.json" ] } 我想在列表的x行和y行之间添加一个新行(步骤)。比如说,如果我需要为步骤“1”添加操作编号“2”(strin

我有以下代码块:

{
  "operation_machine": "Ford",
  "operation_steps": [
    "steps/Step_1/01_paint_the_car.json",
    "steps/Step_2/01_drive_the_car.json",
    "steps/Step_2/02_park_the_car.json"
  ]
}
我想在列表的x行和y行之间添加一个新行(步骤)。比如说,如果我需要为步骤“1”添加操作编号“2”(string=wax_the_the_car),那么它的结尾将如下所示:

{
  "operation_machine": "Ford",
  "operation_steps": [
    "steps/Step_1/01_paint_the_car.json",
    "steps/Step_1/02_wax_the_car.json",
    "steps/Step_2/01_drive_the_car.json",
    "steps/Step_2/02_park_the_car.json"
  ]
}
我刚刚进入AWK,但我想我需要先把这本书读10遍,然后才能独自完成。
我需要你们的帮助。

简单地使用
sed
如下:

sed -i '/text you know is there/ a the line you want to beneath it' file
awk '/steps\/Step\_1\/01\_paint\_the\_car\.json/{print $0 `RS` "    \"line1\"" RS "    \"line2\"";next}1' input_file
在您的示例中:

sed -i '/paint_the_car/ a "steps/Step_1/02_wax_the_car.json",' file
此示例需要
GNU-sed

如果您想自动格式化,
a
并不适合,因为它不知道匹配的行,并且您无法真正使其有意识。 这是可行的,但不像第一个那么简单:

sed -i '/paint_the_car/ s_\([ \t]*\).*_&\n\1"steps/Step_1/02_wax_the_car.json",_' file
\(something\)
将匹配某个内容,稍后可以使用
\1
引用。
&
将引用替换命令第一部分中匹配的整个字符串。

awk
来拯救

$ awk '/Step_2\/01/{print ">>> new line here <<<"}1' file
{
  "operation_machine": "Ford",
  "operation_steps": [
    "steps/Step_1/01_paint_the_car.json",
>>> new line here <<<
    "steps/Step_2/01_drive_the_car.json",
    "steps/Step_2/02_park_the_car.json"
  ]
}

$awk'/Step_2\/01/{print”>>>此处新行如果要使用awk,可以执行以下操作:

sed -i '/text you know is there/ a the line you want to beneath it' file
awk '/steps\/Step\_1\/01\_paint\_the\_car\.json/{print $0 `RS` "    \"line1\"" RS "    \"line2\"";next}1' input_file
说明

首先匹配模式
'/pattern/'
,然后使用RS(记录分隔符,默认值newline)打印当前行
print$0
您要求插入一个新行,然后添加实际的新行,因为最后的
1
next
跳过已打印的行

请记住保护awk模式匹配中的特殊字符

另请注意空格:

"    \"new line1"
 ^^^^
调整格式。您还可以使用
\t
:“
\t新行1
”使用选项卡自动设置格式

然后必须保存awk命令的结果:

awk 'command above' > out_file
这可能适用于您(GNU-sed):

匹配字符串,打印它,替换字符串并打印结果


注意:
\\\\\\\\\\\
使用
\\
作为匹配分隔符(当使用替换命令
s/../../
时,无需引用第一个分隔符)。此外,空匹配使用最后一个分隔符作为默认值。最后,匹配中的元字符应被引用,即
[
]
etc应该是
\.
\[
\]
etc

为什么要使用文本处理工具编辑JSON?为什么不使用JSON处理工具呢?因为这是我必须要做的环境。:)不确定原因,但这只打印块的旧版本,没有插入任何换行符。:(它只会在模式
步骤2/01
之前插入一行。如果您的数据文件没有这一行,它将不会打印任何额外的内容。您可以将其替换为任何其他唯一的模式。当然,您可以使用ANSI C引号编写制表符,就像这样
$'word\tword after tabstop'
。但是自动格式化并不像这样简单。For一个更复杂的答案,请看我编辑的答案。谢谢你,很抱歉回答晚了!