Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

remove pathname

Status
Not open for further replies.

7Star

Technical User
Nov 17, 2005
13
SE
I have a variable that contain a path like /home/test/file.jpg and I want to get only the filename out of the whole path, filename.jpg, any idea how to do that?

/ Ola
 
The [tt]basename[/tt] and [tt]dirname[/tt] functions do this.
As in
[tt]a=`basename $file`[/tt]

--
 
thx, exactly what I was looking for!
 
Below are ksh function replacements for basename and dirname:

# Using ksh pattern-matching operators, this function
# replaces the unix basename command. If a 2nd argument
# exists, strip off the extension.
function basename {
typeset v x

v=${1##*/}
x=${2#.} # get rid of the '.'
v=${v%.$x}
echo $v
}


# Using ksh pattern-matching operators, this function
# replaces the unix dirname command.
function dirname {
typeset v="$@"

echo ${v%/*}
}

# basename and dirname function examples
var=/usr/eds/ddir/ttest.c

bn=$(basename $var)
echo $bn # displays: ttest.c

bn=$(basename $var .c)
echo $bn # displays: ttest

dn=$(dirname $var)
echo $dn # displays: /usr/eds/ddir
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top