Home > Blockchain >  Two same string in file but need replace the word in second string
Two same string in file but need replace the word in second string

Time:04-01

I have file which contain below string in file.

ALTER DATABASE RENAME FILE '/home/oracle/oradata/undotbs01.dbf' TO '/home/oracle/oradata/undotbs01.dbf';

With bash methods I want to replace second "undotbs01.dbf" to another name. When I did it with grep and sed it changes all undotbs01 words in file, to the new value. But I need only second undotbs (which located after "TO" word) to be changed.

CodePudding user response:

With sed back-references this is what I suggest:

$ cat in
ALTER DATABASE RENAME FILE '/home/oracle/oradata/undotbs01.dbf' TO '/home/oracle/oradata/undotbs01.dbf';
$ sed -e "s,\(.*/\).*\(dbf.*\),\1newname.\2," < in
ALTER DATABASE RENAME FILE '/home/oracle/oradata/undotbs01.dbf' TO '/home/oracle/oradata/newname.dbf';

This uses the greedyness of the first .* pattern (i.e. it wants to match as much as possible).

CodePudding user response:

Suggesting an awk script:

awk script:

awk '{sub(".*",str,$(NF-1));print}' FS="'" OFS="'" str="123"

results in:

awk '{sub(".*",str,$(NF-1));print}' FS="'" OFS="'" str="123" <<< $(echo "ALTER DATABASE RENAME FILE '/home/oracle/oradata/undotbs01.dbf' TO '/home/oracle/oradata/undotbs01.dbf';")
ALTER DATABASE RENAME FILE '/home/oracle/oradata/undotbs01.dbf' TO '123';

instructions:

Put replacement string in str="value" or variable name $var str="$var"

Explanation

FS="'" set awk field separator to '

OFS="'" set awk output field separator to '

sub(".*",str,$(NF-1)) substitute/replace value of (last field - 1) with str value. The last field $FN is the termination ;

CodePudding user response:

Using sed

sed 's/undotbs01\.dbf/new_value/2' input_file
ALTER DATABASE RENAME FILE '/home/oracle/oradata/undotbs01.dbf' TO '/home/oracle/oradata/new_value';
  • Related