Wanted: How to strip off pathnames to obtain filenames.

Chris Torek chris at mimsy.UUCP
Fri Sep 2 13:17:17 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.

>   filename=`echo $pathname | cut -fLAST -d/"	# no such thing -fLAST
>or
>   IFS=/
>   set $pathname	
>   filename=$`$#`		# I know this does not work

Actually, the latter almost works; the command

	eval 'filename=$'$#

works every time . . . until there are 10 or more components to the
path name.  `$13' produces $1 followed by the character 3, not the
thirteenth argument.  (Grr :-) )

There is a C-shell built-in that does it:

	set filename=$pathname:t	# or, better, :t:q

but you may not have the C shell available.

In that case, sed to the rescue!:

	filename=`echo $pathname | sed 's,.*/,,'`

>I know the following script does work (by brute force) but I could not put
>it in the same script (pathname args will be wiped out by the "set" command).
>
>	while [ "$#" -gt 1 ]
>	do
>		shift
>	done
>	echo $1

True.  But here is a strange thought: one can make all variables
`local' by using `-evaluation and subshells:

	filename=`while [ $# -gt 1 ]; do shift; done; echo $1`
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.unix.questions mailing list