0

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/

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

3 Answers3

3
  1. Using cut (tacking on the final /):

    ORACLE_HOME=$(printf "%s" "$ORACLE_HOME" | cut -d/ -f1-3)/
    
  2. 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"}
    
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
0

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/
DopeGhoti
  • 76,081
0

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
$