0

Input file (has 2 lines with 2 key value pairs):

key1 = "x"
key2 = ['a', 'b', 'c']

Using this input file, I need to replace the key value pair on another file.

File1 (got 2 lines with 2 key value pairs):

key1 = "y"
key2 = ['p' , 'q', 'r']

Please let me know if there is any easy way in shell script to do this task.

1
  • 1
    I'm confused. What is the intended output? May 9, 2020 at 3:15

1 Answer 1

0

Not entirely sure what you want to archive. Assuming you want to patch a file file.txt containing text and your key value pairs like this

key1
key2
text
key1 = "original"
key2 = ['o' , 'r', 'i', 'g']
text

with a patchfile.txt only containing the key value pairs of the values you want to replace, like this

key1 = "patched"
key2 = ['p', 'a', 't', 'c', 'h']

without overwriting the text key1/key2 that isn't a key value pair to get a file.txt like this

key1
key2
text
key1 = "patched"
key2 = ['p', 'a', 't', 'c', 'h']
text

by issuing a command like this

patchmystuff.sh file.txt patchfile.txt

The content of patchmystuff.sh could look like this:

#!/usr/bin/env bash

original_file=$1
patch_file=$2

# loop from here:
# https://stackoverflow.com/questions/1521462/looping-through-the-content-of-a-file-in-bash
while IFS="" read -r line || [ -n "$line" ]
do
    printf 'patching %s\n' "$line"
    # (?<==) is the lookbehind for = to keep it
    # otherwise it will match key1/key2 in regular text
    search_string=$(echo "$line" | perl -ne 's/(?<==).*//g; print;')
    printf 'search string: "%s"\n' "$search_string"
    sed -i -e "s/$search_string.*/$line/g" "$original_file"
done < "$patch_file"
2
  • Thank you so much! Worked fine for me!! I was able to update file using sed -i option. So I dont have to create any temporary file.
    – Rajeesh
    May 10, 2020 at 23:09
  • You're right, that's a better option. I adjusted my answer.
    – id -un
    May 12, 2020 at 18:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .