How to search using variable to match any string -

2019-08-22 18:36发布

How to search part of the string using variable and assign to new variables

My Search variable is : db_uni_name=testdb_iac3bd

My Oratab File is:

+ASM1:/u01/app/12.2.0.1/grid:N
oidiaddb:/u02/app/oracle/product/12.2.0/dbhome_2:Y
testdb:/u02/app/oracle/product/12.2.0/dbhome_3:Y
oradb:/u02/app/oracle/product/12.2.0/dbhome_4:Y

I want to search $db_uni_name to find matching db name and path

In this case, i want to search for testdb and assign as follows:

DB_NAME=testdb
ORACLE_HOME=/u02/app/oracle/product/12.2.0/dbhome_3

标签: shell unix
2条回答
祖国的老花朵
2楼-- · 2019-08-22 19:15

Try this:

mayankp@mayank:~/Documents$ DB_NAME=$(echo $db_uni_name | grep `awk -F'_' '{print $1}'` Oratab.txt | awk -F ':' '{print $1}')
mayankp@mayank:~/Documents$ echo $DB_NAME
testdb
mayankp@mayank:~/Documents$ ORACLE_HOME=$(echo $db_uni_name | grep `awk -F'_' '{print $1}'` Oratab.txt | awk -F ':' '{print $2}')
mayankp@mayank:~/Documents$ echo $ORACLE_HOME 
/u02/app/oracle/product/12.2.0/dbhome_3

Let me know if this helps.

查看更多
Deceive 欺骗
3楼-- · 2019-08-22 19:25

Here another way to print out the values.

$ awk -F: -v patt=${db_uni_name%_*} \
 '$0~patt{print "DB_NAME="$1; print "ORACLE_HOME="$2}' inputFile
DB_NAME=testdb
ORACLE_HOME=/u02/app/oracle/product/12.2.0/dbhome_3

It uses %_* to separate testdb from _iac3d. Then use awk to search and print.

If you want to export those variables in the current shell, then use the following, which adds export to the print and then evaluates using $()

$ $(awk -F: -v patt=${db_uni_name%_*} '$0~patt{print "export DB_NAME="$1; print "export ORACLE_HOME="$2}' inputFile)
$ echo $DB_NAME
testdb
$ echo $ORACLE_HOME
/u02/app/oracle/product/12.2.0/dbhome_3
查看更多
登录 后发表回答