Wanted: How to strip off pathnames to obtain filenames.

Wolf N. Paul wnp at dcs.UUCP
Fri Sep 2 22:12:02 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

YES! basename(1) does exactly what you want!


	filename=`basename $pathname`

will yield the part of $pathname to the right of the last slash;

	filename=`basename $pathname .ext`

will yield the part of the pathname to the right of the last slash, minus
the extension ".ext".

Under System V Release 2, basename(1) is a shell script, so even if it does
not exist on your system (why would that be?) I'm sure you can find it 
somewhere within your organization (your corporate security wouldn't like
it if I posted it :-)).

However, this is also very straightforward to do in C:

#include <stdio.h>
#include <string.h>
main(argc, argv)
int argc;
char **argv;
{
	char *ptr;

	ptr=strrchr(argv[1], '/');
	*ptr++;
	puts(ptr);
}

Of course, if you are using C-Shell, things are even simpler:

	set filename=$pathname:t     # = basename $pathname
	set filename=$pathname:t:r   # = basename $pathname .*

etc.

-- 
Wolf N. Paul * 3387 Sam Rayburn Run * Carrollton TX 75007 * (214) 306-9101
UUCP:     killer!dcs!wnp                 ESL: 62832882
DOMAIN:   dcs!wnp at killer.dallas.tx.us    TLX: 910-380-0585 EES PLANO UD



More information about the Comp.unix.questions mailing list