Operating System - HP-UX
1825778 Members
2260 Online
109687 Solutions
New Discussion

quick one: cut'ing or seding directory path to get just the filename

 
SOLVED
Go to solution
Bill McNAMARA_1
Honored Contributor

quick one: cut'ing or seding directory path to get just the filename

Hi all,

If I have a variable $F
that looks something like the following:
/usr/bin/dothis.ksh
and or
/usr/contrib/bin/dothat.ksh

what's the best way to extract the filename
echo $F | nice -and -sweet

Thanks!
Bill
It works for me (tm)
7 REPLIES 7
Santosh Nair_1
Honored Contributor

Re: quick one: cut'ing or seding directory path to get just the filename

How about using the basename command? Is that what you're looking for?

-Santosh
Life is what's happening while you're busy making other plans
Santosh Nair_1
Honored Contributor
Solution

Re: quick one: cut'ing or seding directory path to get just the filename

I guess I should have been a bit more descriptive...i.e.

FILENAME=$(basename $F)

not sure if this is a requirement, but you can also strip of the suffix,i.e.:

if $F=/usr/contrib/bin/something.ksh

FILENAME=$(basename $F .ksh)

$FILENAME should be set to the word something.

-Santosh
Life is what's happening while you're busy making other plans
Bill McNAMARA_1
Honored Contributor

Re: quick one: cut'ing or seding directory path to get just the filename

nice one santosh,
That was just what I was looking for..

It would have saved me so much pain if I knew about that around a year ago!!

Thanks again,
Bill
It works for me (tm)
Santosh Nair_1
Honored Contributor

Re: quick one: cut'ing or seding directory path to get just the filename

You're welcome.

Also just FYI, you can use the dirname command to get the directory part of the full path. Its complimentary to the basename command.

-Santosh
Life is what's happening while you're busy making other plans
Volker Borowski
Honored Contributor

Re: quick one: cut'ing or seding directory path to get just the filename

Hi,

something I learned yesterday from this forum:
This solution will not cover filenames with blanks! Enclose $F in double quotes !

# echo $F
/tmp/a b c
# FILENAME=$(basename "$F")
# echo $FILENAME
a b c
#

Volker
David Lodge
Trusted Contributor

Re: quick one: cut'ing or seding directory path to get just the filename

basename works and is easy to remember, for efficiency you may try using the quick shell construct:

NewPath=${F##*/}

(Essentially NewPath = $F but remove the largest section from the front of F which matches the glob '*/')

dave
(shell should be efficient :-)
Steve Post
Trusted Contributor

Re: quick one: cut'ing or seding directory path to get just the filename

I did not know about dirname and basename either. I ended up doing this:

LIST=`echo "$1" | sed 's#/# #g' `
for I in $LIST
do
LASTI=$I
done
echo $LASTI

Where $1 is your fullpath'd file /a/b/c/file1
.....or as said above: basename $1