I need to extract the first 2 directories in a path that is in the variable $ORACLE_HOME
ORACLE_HOME=/oradba/app/oracle/product/11.2.0.4/testdb
I need the value: /oradba/app/
I need to extract the first 2 directories in a path that is in the variable $ORACLE_HOME
ORACLE_HOME=/oradba/app/oracle/product/11.2.0.4/testdb
I need the value: /oradba/app/
Using cut (tacking on the final /
):
ORACLE_HOME=$(printf "%s" "$ORACLE_HOME" | cut -d/ -f1-3)/
Using parameter expansion twice; the first strips away the first two elements of the directory, then the second strips that remainder away from the original variable:
suffix=${ORACLE_HOME#/*/*/}
ORACLE_HOME=${ORACLE_HOME%"$suffix"}
Two alternatives. The latter is more convoluted, but safer as it doesn't require you to know how many directories are in the variable:
$ echo ${ORACLE_HOME%/*/*/*/*}/
/oradba/app/
$ echo $ORACLE_HOME | awk -F/ 'BEGIN {OFS="/"} {print $1,$2,$3,""}'
/oradba/app/
Try:
echo $ORACLE_HOME | cut -d/ -f-3
For example:
$ ORACLE_HOME=/oradba/app/oracle/product/11.2.0.4/testdb
$ echo $ORACLE_HOME | cut -d/ -f-3
/oradba/app
$