grep a pattern and replace a value in it and write to the same file.

I have some complication with this, I have a file like below[db.sh] for DEV_1 till DEV_10. and the db values are set accordinly which are not unique. For example DEV1,DEV4,DEV6 can have the same target DB name.
I waned to identify[grep] for DEV_2 and then replace the TARGET_DATABASE value with the new DB name, can you suggest.

DEV_1_SOURCE_DATABASE=server1
DEV_1_SOURCE_AUDIT_DATABASE= server1
DEV_1_TARGET_DATABASE=server4
DEV_1_TARGET_AUDIT_DATABASE=server4

DEV_2_SOURCE_DATABASE=server2
DEV_2_SOURCE_AUDIT_DATABASE= server2
DEV_2_TARGET_DATABASE=server5
DEV_2_TARGET_AUDIT_DATABASE=server5
.
.
.
.
.
.

i used sed like sed 's/`cat db.sh | grep -i DEV_2 | grep -i database | egrep -v "audit|source"`/newdbname' < db.sh > db.sh_new
i got a error;
tried awk but dint work as i am trying to pass command on:
can someone help in this :
my ultimate need is i need to grep a pattern and replace the value in that location only,

this might be too long !!!!

can you post the required output?

In case new db name is "UNIX",
Are you expecting the output as follows?

DEV_1_SOURCE_DATABASE=server1
DEV_1_SOURCE_AUDIT_DATABASE= server1
DEV_1_TARGET_DATABASE=server4
DEV_1_TARGET_AUDIT_DATABASE=server4

DEV_2_SOURCE_DATABASE=server2
DEV_2_SOURCE_AUDIT_DATABASE= server2
DEV_2_TARGET_DATABASE=UNIX
DEV_2_TARGET_AUDIT_DATABASE=server5

Is this what your expecting?

yes, u are right,, i expect the outut as above,,

but i would like to rremind that the original file contains "server4" as a value for more than one DB target,, i mean not only DEV_2 target is server4 but also say DEV_3 will be targetted to server4.

This may help you.

sed 's/\(DEV_2_TARGET_DATABASE=\)\(.*\)/\1UNIX/g' t1

ope the file in vi editor

1.hit esc .
2. Type %s/"pattern to be matched"/"pattern to be replaced"/g

This will replace all the instances of pattern to be matched

since i could not get your expectation clearly,
Here am giving some solution

$cat file

DEV_1_SOURCE_DATABASE=server1
DEV_1_SOURCE_AUDIT_DATABASE= server1
DEV_1_TARGET_DATABASE=server4
DEV_1_TARGET_AUDIT_DATABASE=server4

DEV_2_SOURCE_DATABASE=server2
DEV_2_SOURCE_AUDIT_DATABASE= server2
DEV_2_TARGET_DATABASE=server5
DEV_2_TARGET_AUDIT_DATABASE=server5

Solution 1:

script1.sh
a=` cat file | grep -w "DEV_2_TARGET_DATABASE" | cut -d '=' -f 2`
sed "s/\($a\)/newdb/g" file > file1
mv file1 file

The above script will take the value assigned for DEV_2_TARGET_DATABASE, and substitute that value i.e "server5" to newdb in the whole file content. ( even for DEV 4 or DEV 3)

Solution 2:

If you want to substitute only DEV_2_TARGET_DATABASE=server5 to DEV_2_TARGET_DATABASE=newdb

sed "s/\(DEV_2_TARGET_DATABASE=\)\(.*\)/\1newdb/g" file

Hope this helps..