![](/img/trans.png)
[英]Insert multiple lines into a file after specified pattern using shell script
[英]Insert multiple lines into a file using shell script
我想使用 shell 脚本在特定模式后将多行插入到 a.json 文件中。 还需要考虑在第n次出现时插入。
让我们考虑一下我的输入文件内容是:input.txt:
[
{
"a": "a",
"b": "b"
},
{
"c": "c",
"d": "d"
},
{
"e": "e",
"f": "f"
}
]
在我的第一种情况下,我必须在 input.txt 文件中第一次出现模式“}”之后插入两行,而在我的第二种情况下,我必须在第二次出现模式“}”之后插入相同的两行
插入我的文件后应该像这样改变:
第一种情况:插入x & y条目
[
{
"a": "a",
"b": "b"
},
{
"x": "x",
"y": "y"
},
{
"c": "c",
"d": "d"
},
{
"e": "e",
"f": "f"
}
]
第二种情况:插入m&n条目
[
{
"a": "a",
"b": "b"
},
{
"c": "c",
"d": "d"
},
{
"m": "m",
"n": "n"
}
{
"e": "e",
"f": "f"
}
]
我在我的 shell 脚本中使用sed命令尝试这个。 但这总是在第一次出现而不是第 n次出现时替换。
sed -e '0,/},/{//a\ {\n "x",\n "y"\n },' -e '}' input.txt file
谁能帮我?
如果它是您打算重复使用的东西,您可以在 python 中进行。
#! /usr/bin/env python3
import json
import sys
j = json.load(sys.stdin)
j.insert(int(sys.argv[1]), json.loads(sys.argv[2]))
print(j)
你可以调用它传递 position 和 object 作为参数
./json-insert 1 '{"x": "x", "y": "y"}' < input.json
cat file.json|tr '\n' ' '| sed 's/},/},{"x":"x", "y":"y"},/2'|json_pp
[
{
"a" : "a",
"b" : "b"
},
{
"c" : "c",
"d" : "d"
},
{
"x" : "x",
"y" : "y"
},
{
"e" : "e",
"f" : "f"
}
]
#------------------------------------------------ --------------
cat file.json|tr '\n' ' '| sed 's/},/},{"x":"x", "y":"y"},/2'|json_pp > tmp.json
mv tmp.json file.json
这可能对你有用(GNU sed & Bash):
cat <<\! | sed -Ee '/\}/{x;s/^/x/;/^x{1}$/{x;r /dev/stdin' -e 'x};x}' file
{
"x": "x",
"y": "y"
},
!
或者:
cat <<\! | sed -Ee '/\}/{x;s/^/x/;/^x{2}$/{x;r /dev/stdin' -e 'x};x}' file
{
"m": "m",
"n": "n"
},
!
Pipe 字符串将通过/dev/stdin
插入到 sed 调用中,使用保持空间中的计数器来启动字符串的放置。
注意r
命令必须由换行符终止,因此使用-e
命令选项将 sed 命令分成两部分的原因。 可以将字符串收集在一个 here-document 中,并使用cat
命令传递到以下 pipe 的/dev/stdin
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.