1

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!

alva
  • 72
  • 8
  • Why can't you save the previous string in a variable? `path_str=$(command)` saves the output of a command in a variable. – Barmar Aug 27 '15 at 09:54
  • Indeed I would do so, but the point of the question is not how to save a string in a variable, but how to truncate part of it. Thank you. – alva Aug 27 '15 at 10:23
  • Sorry, it looked like you already knew how to use expansion operators to truncate part of it. – Barmar Aug 27 '15 at 10:24

2 Answers2

3

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.

Community
  • 1
  • 1
Alepac
  • 1,833
  • 13
  • 24
1

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
Jens
  • 69,818
  • 15
  • 125
  • 179
  • Thank you very much, this is exactly what I was looking for. May you point me to the documentation of the syntax you have used? – alva Aug 27 '15 at 10:24
  • @alva It's documented in the bash manual, in the section on parameter expansion. – Barmar Aug 27 '15 at 10:24
  • http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html#Shell-Parameter-Expansion – Barmar Aug 27 '15 at 10:25