Skip to content
Advertisement

Read first line in a file and append it to first occurrence of the search string and Repeat until EOF

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

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement