2

how to extract path location from below given string.

/opt/oracle/app/oracle/product/12.1.0/bin/tnslsnr

expected output.

/opt/oracle/app/oracle/product/12.1.0/bin

(or)

/opt/oracle/app/oracle/product/12.1.0/bin/
Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
ABUL KASHIM
  • 627
  • 3
  • 8
  • 10

2 Answers2

7

Use the shell's suffix removal feature

str=/opt/oracle/app/oracle/product/12.1.0/bin/tnslsnr
path=${str%/*}
echo "$path"

In general, ${parameter%word} removes word from the end of parameter. In our case, we want to remove the final slash and all characters which follow: /*.

The above produces:

/opt/oracle/app/oracle/product/12.1.0/bin

Use dirname

dirname can be used to strip the last component from a path:

$ dirname -- "$str"
/opt/oracle/app/oracle/product/12.1.0/bin
cuonglm
  • 150,973
  • 38
  • 327
  • 406
John1024
  • 73,527
  • 11
  • 167
  • 163
0
start cmd:> dirname "/opt/oracle/app/oracle/product/12.1.0/bin/tnslsnr"
/opt/oracle/app/oracle/product/12.1.0/bin

file_path="/opt/oracle/app/oracle/product/12.1.0/bin/tnslsnr"
dir_path_woslash="${file_path%/*}"
echo "$dir_path_woslash"
/opt/oracle/app/oracle/product/12.1.0/bin

shopt -s extglob
dir_path_wslash="${file_path%%+([^/])}"
echo "$dir_path_wslash"
/opt/oracle/app/oracle/product/12.1.0/bin/
Hauke Laging
  • 88,146
  • 18
  • 125
  • 174