I recently discovered a new trick for using basename to extract filenames from a full pathnames.
In the normal use of the command, basename strips the path from a file or directory reference, leaving just the name of the particular file or directory. The path "/etc/hosts" becomes "hosts" and "/var/spool/cron/crontabs/adm" becomes "adm". Simple enough. The partner of the basename command, dirname, does just the opposite. It strips off the file or directory name, leaving only the path.
boson> basename /etc/hosts
hosts
boson> dirname /etc/hosts
/etc
|
You can, however, also strip off a file's (or a directory's) extension by adding the particular extension to the end of your basename command as shown in these examples:
boson> basename /etc/syslog.conf .conf
syslog
boson> basename /etc/init.d .d
init
|
The extra argument is referred to as a "suffix" in the basename man page.
This beats the socks off having to tack on a pipe and a call to some additional tool, such as this example using sed:
boson> basename /etc/syslog.conf | sed "s/.conf//"
syslog
|
Of course, the arguments that you pass to the basename and dirname commands don't actually have to be paths. They don't have to exist on your system or any system for that matter. They just have to look like paths. The basename command will strip off everything up to and including the final slash (/) in just about any string that you feed it and the dirname will strip off everything starting with and including the final slash. These examples prove the point:
boson> numerator=`dirname 1/2`
boson> echo $numerator
1
boson> denominator=`basename 1/2`
boson> echo $denominator
2
|
If the string, path or otherwise, that you want to reduce contains blanks, just enclose your string in quotes and basename will get to work on it. In this example, basename breaks the string on the slash as agreeably as it would an actual path:
boson> basename "I want to buy 1/4 cow"
4 cow
|
In fact, the basename suffix can be used to remove larger portions of file names if you are inclined to use it that way. There is no constrain that says you can only remove a string that starts with a dot.
You can remove multiple extensions:
boson> basename /etc/syslog.conf.old .conf.old
syslog
|
You can remove everything up to the first letter of a file's name:
boson> basename /etc/path_to_inst.old ath_to_inst.old
p
|
This trick can be useful if you want to extract some portion of a file's name and then reuse it. For example, if you want to find the differences between a number of files with .old extensions and the original files, you could do this:
boson> for file in `ls *.old`
> do
> diff $file `basename $file .old`
> done
|
This little trick with basename will probably come in very handy from time to time.