Reputation: 77
I have a file with following lines in a text file in following format
"abc": "xyz",
"qwe": "uva",
"asd": "lkj",
And a json file in following format
{
"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",
},
Now i want output of json as follows
{
"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",
},
So how can achieve this using bash?
I've tried with following but it only appends last line of the file.
#!/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
Upvotes: 1
Views: 165
Reputation: 5975
you can use awk
to add these lines.
awk 'FNR==NR{a[NR]=$0; next} /solution-id/{$0=$0 "\n\t" a[++i]} 1' lines file
i
restart from the beginning, for example like this:
awk 'FNR==NR{a[NR]=$0; next} /solution-id/{$0=$0 "\n\t" a[i++%length(a)+1]} 1' lines file
Upvotes: 1
Reputation: 5785
This will do it:
#!/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
Upvotes: 1
Reputation: 58473
This might work for you (GNU sed):
sed 's/^/ /' textFile | sed '/solution-id/R /dev/stdin' jsonFile
Prepend 4 spaces to each line of the text file and pipe the results to the second invocation of sed which appends the lines (one at a time) to the json file when matching on the string solution-id
.
Upvotes: 0
Reputation: 3273
If your solution-id
identifiers match the order with your file here is the code that does what you need:
#!/usr/bin/env bash
x=0
cp sample.json tmp.json
while read l
do
sed -i "/\"solution-id\": ${x},/a ${l}" tmp.json
x=$(($x + 1))
done < names.txt
cat tmp.json
It copies your input file and performs sed replacements in place and prints it at the end.
Upvotes: 0