gpt4 book ai didi

linux - 读取文件中的第一行并将其附加到搜索字符串的第一次出现处并重复直到 EOF

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:05:30 24 4
gpt4 key购买 nike

我在一个文本文件中有一个包含以下行的文件,格式如下

"abc": "xyz",
"qwe": "uva",
"asd": "lkj",

和一个格式如下的json文件

{
"svn-user-id": "passwd"
"solution-id": 0,
"cronos-id": "1",
"solution-state": "active",
},
{
"svn-user-id": "passwd"
"solution-id": 1,
"cronos-id": "1",
"solution-state": "active",
},
{
"svn-user-id": "passwd"
"solution-id": 2,
"cronos-id": "1",
"solution-state": "active",
},

现在我想要json的输出如下

{
"svn-user-id": "passwd"
"solution-id": 0,
"abc": "xyz",
"cronos-id": "1",
"solution-state": "active",
},
{
"svn-user-id": "passwd"
"solution-id": 1,
"qwe": "uva",
"cronos-id": "1",
"solution-state": "active",
},
{
"svn-user-id": "passwd"
"solution-id": 2,
"asd": "lkj",
"cronos-id": "1",
"solution-state": "active",
},

那么如何使用 bash 实现这一点呢?

我试过以下但它只附加文件的最后一行。

#!/bin/bash
set -x
file=names.txt #file has list of lines as described above
IFS=$'\n'

for l in `cat $file`
do
echo $l
sed '/"solution-id": 1,/a \'"$l"'' sample.json # json file as described above
done

最佳答案

这样做就可以了:

#!/bin/bash
#set -x
IFS=$'\n'

declare -a names
names=(`cat names.txt`)

for l in `cat sample.json`
do
echo $l
echo $l | grep -P -q solution-id
if [ $? -eq 0 ]
then
echo " ${names[$i]}"
let "i+=1"
fi
done

关于linux - 读取文件中的第一行并将其附加到搜索字符串的第一次出现处并重复直到 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47475017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com