alva
alva

Reputation: 72

truncate a string in bash with variable expansion formatting

I am trying to truncate a string in bash, specifically to get into the directory of an executable linked by a symlink. For example:

[alva@brnzn ~ $] ls -algh $(which python3.4)
lrwxr-xr-x  1 admin    73B 26 May 02:49 /opt/local/bin/python3.4 -> /opt/local/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4

So i cut out the fields I don't need:

[alva@brnzn ~ $] ls -algh $(which python3.4) | cut -d" " -f 14
/opt/local/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4

I need help to cut out everything after the last /. I am interested in a solution were I can save the previous string in a var and using variable expansion to cut out the part of the string I dont need. e.g. printf '%s\n' "${path_str#*/}" (this is just an example).

Thank you!

Upvotes: 1

Views: 2337

Answers (2)

Alepac
Alepac

Reputation: 1831

You can use dirname to retrieve the final directory-name and than assign it to a variable, so the solution could be:

MY_VAR=$( dirname $(ls -algh $(which python3.4) | cut -d" " -f 14) )

But I prefer to use readlink to show the linked file so your code should be:

MY_VAR=$( dirname $( readlink $(which python3.4) )

Take a look to How to resolve symbolic links in a shell script to read the full history.

Upvotes: 3

Jens
Jens

Reputation: 72647

Would this be what you need?

$ x=/opt/local/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4
$ echo ${x%/*}
/opt/local/Library/Frameworks/Python.framework/Versions/3.4/bin

Upvotes: 1

Related Questions