Copy a content from one file and need to replace in another file using sed

Viewed 953

Here, we have two files. we need to copy a key from file 1 and need to replace in file 2 with specific string "key" using sed command. we tried with below commands:

sed -e '3 /key/{r file1' -e 'd}' file2

sed  -n "3 s/key/$(cat file 1 |grep ^Key|cut -d ' ' -f2)/" file2

File 1

ABCD
EFGH 
Key: qvUkD6QaFBA1jYEpynivMoQx+9V71F4+fdn1TIUKPBNny/3zCnjihd1mwxZg==

File 2

IJKL
MNOP
secret key;
MNOP

Expected result:

IJKL
MNOP
secret qvUkD6QaFBA1jYEpynivMoQx+9V71F4+fdn1TIUKPBNny/3zCnjihd1mwxZg==;
MNOP
2 Answers

This might work for you (GNU sed):

sed -nE '/Key: /{s///;s/\W/\\&/g;s#.*#s/"key"/&/#p}' file1 | sed -Ef - file2

Craft a substitution command from file1 not forgetting to quote non-word characters.

Pass the sed substitution command as stdin, to a second invocation of sed via the -f option and use it to edit file2.

awk

I am not sure how efficient my code will be for your usage.

awk ' /^Key/{q=$2;next} /A|E/{$0=""; next}/^secret/{$2="\""q"\";"}1' $file1 $file2
$ awk ' /^Key/{q=$2;next} /A|E/{$0=""; next}/^secret/{$2="\""q"\";"}1' $file1 $file2
IJKL
MNOP
secret "qvUkD6QaFBA1jYEpynivMoQx+9V71F4+fdn1TIUKPBNny/3zCnjihd1mwxZg==";
MNOP

Here, I am matching any line starting with the Key and secret string and substituting their values.

sed

You will need to create a variable to fetch the key first.

key=$(sed '1,2d;s/Key: //' $file1) or key=$(awk 'NR==3{print $2}' $file1)

$ echo $key
qvUkD6QaFBA1jYEpynivMoQx+9V71F4+fdn1TIUKPBNny/3zCnjihd1mwxZg==

The following code will generate your expected result, but once again, I am not sure how efficient it will be for your usage.

sed "/^secret/s|key|$key|" $file2
$ sed "/^secret/s|key|$key|" $file2
IJKL
MNOP
secret "qvUkD6QaFBA1jYEpynivMoQx+9V71F4+fdn1TIUKPBNny/3zCnjihd1mwxZg==";
MNOP
Related