Wanted: How to strip off pathnames to obtain filenames.

Tim J Ihde tim at attdso.ATT.COM
Fri Sep 9 07:35:52 AEST 1988


In article <5968 at ihlpf.ATT.COM> pcl at ihlpf.ATT.COM (pcl) writes:
>My question is, given a full or partial pathname, how to obtain the
>last field (which is the filename) in a straight foward manner.
>
>Is there such command that does 
>   filename=`echo $pathname | cut -fLAST -d/"	# no such thing -fLAST

The basename and dirname commands will do this, as I'm sure someone has
said by now.

For yet another path parser, you could do this with the much underutilized
expr command as well (at least on System V; I can't remember if BSD
does this or not).  In addition to doing math, expr will match regular
expressions for you and return part of the expression on stdout.  To
emulate basename you could use
	
	filename=`expr $pathname : '.*/\(.*)'`

The second regular expression in parenthesis is returned on stdout.
Note that the parens themselves must be escaped (if you don't include
any parens then expr returns the number of characters it matched).
These are ed style r.e.'s; so you need ".*" and not just "*" as a wildcard.
Since the first r.e., ".*/", will match as much as possible from $pathname, the
.* in the parens will always be the filename.

This is a more general path parser, since it could also return, say, the
last directory in the path before the filename:

	lastdir=`expr $pathname : '.*/\(.*)/.*'`

The use for such a beast is left as an exercise.  I've found

	suffix=`expr $pathname : '.*\.\(.*\)'`

to pull the "c" out of "file.c" useful several times.
-- 
Tim J Ihde					att!attdso!tim
(201) 898-6687					tim at attdso.att.com
This disclaimer intentionally left blank.  	attmail!tihde



More information about the Comp.unix.questions mailing list