I'm trying to set a variable in an sh script to the last 3 characters of the base name of a file (by base name I mean without the path and without the suffix). I've succeeded in doing this but, purely out of curiosity, I'm wondering if there is a shorter, single command I can use. Originally I had a one-liner with awk
, but it was rather long. Currently I have this two-line script (assuming a complete filename is in $1
):
filebase=`basename "$1"`
lastpart=`echo -n ${filebase%.*} | tail -c3`
So for example, "/path/to/somefile.txt" ends up with "ile" in $lastpart
.
Can I somehow combine basename
and the bit to strip the suffix into a single command, and is there a way to send it to tail
(or something else I can use) without using a pipe? The suffix is unknown so I can't base it as a parameter to basename
.
The main goal isn't actually so much to be as short as possible, as to be as readable at a glance as possible. The actual context of all of this is this question on Superuser, where I'm trying to come up with a reasonably simple answer.
file.one.two.three
? Would you wantile
ortwo
? – terdon Jun 23 '14 at 08:15two
would work; the extension on that would be.three
I guess. – Jason C Jun 23 '14 at 10:34