how to extract path from file location using shell

13,806

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
Share:
13,806

Related videos on Youtube

ABUL KASHIM
Author by

ABUL KASHIM

Updated on September 18, 2022

Comments

  • ABUL KASHIM
    ABUL KASHIM almost 2 years

    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/