Posted on 2012-11-22 22:43:02+00:00
Every so often, my colleagues and I find ourselves stretching Bash to the limits of what it's supposed to do. Often, something like Perl or Python would be better choices for the task at hand. But for a variety of reasons, using those languages is not an option. This post will show you how to take a path like /home/silviogutierrez/www/example.com
and get just example.com
.
For those of you thinking that basename
will do the same thing: while true, that only works for directories and for the last part of the path. The technique shown here lets you explode around periods, hyphens, underscores, etc. It also lets you get other elements besides the last one by using the offsets -2, -3, and so on.
First, let's set our variable:
1 |
|
Then, let's split up the PATH into an array of directories:
1 2 |
|
And finally, let's get the last element. To do this, we first get the length of the array, using the # notation, and then subtract one. To get a length of an
array we just do:
1 2 3 |
|
We can just combine these steps into the shorter version - if harder to read:
1 |
|
And that's it, LAST_PART
should now contain example.com
. Hope that helps.
Here's the full version all in one piece:
1 2 3 |
|
In this particular case, you could also just:
long_path=/home/silviogutierrez/www/example.com last_part=${long_path##*/}
IIRC, this will also work with POSIX /bin/sh, whereas arrays are a bashism.
You can also use sed: echo "/home/silviogutierrez/www/example.com" | sed 's/.*\///'
In this case, you should use another parameter separator for sed for readability: echo "/home/silviogutierrez/www/example.com" | sed 's|.*/||'
Read from http://code.linuxnix.com/2013/02/linuxunix-shell-scriptingprint-last-array-element.html, LAST_PART=${DIRS[@]:(-1)}
The text on this page made my eyes bleed and now I am blind. Where am i?