36.13. Using basename and dirname
Almost every Unix command can use relative and absolute pathnames (Section 31.2) to find a file or directory. There are times you'll need part of a pathname -- the head (everything before the last slash) or the tail (the name after the last slash). The utilities basename and dirname, available on most Unix systems, handle that.
36.13.1. Introduction to basename and dirname
% basename /usr/bin/gigiplot gigiplot % basename /home/mikel/bin/bvurns.sh bvurns.sh
basename can also strip a suffix from a filename. For example:
% basename /home/mikel/bin/bvurns.sh .sh bvurns
% dirname /usr/bin/screenblank /usr/bin % dirname local .
If you give dirname a "pure" filename (i.e., a filename with no path, as in the second example), it tells you that the directory is . (the current directory).
NOTE: dirname and basename have a bug in some implementations. They don't recognize the second argument as a filename suffix to strip. Here's a good test:% basename 0.foo .foo
36.13.2. Use with Loops
Here's an example of basename and dirname. There's a directory tree with some very large files -- over 100,000 characters. You want to find those files, run split (Section 21.9) on them, and add huge. to the start of the original filename. By default, split names the file chunks xaa, xab, xac, and so on; you want to use the original filename and a dot (.) instead of x:
for path in `find /home/you -type f -size +100000c -print` do cd `dirname $path` || exit filename=`basename $path` split $filename $filename. mv -i $filename huge.$filename done
(The absolute pathnames are important here. The cd would fail on the second pass of the loop if you use relative pathnames.) In the loop, the cd command uses dirname to go to the directory where the file is. The filename variable, with the output of basename, is used several places -- twice on the split command line.
If the previous code results in the error command line too long, replace the first lines with the two lines below. This makes a redirected-input loop:
find /home/you -type f -size +100000c -print | while read path
--JP and ML
Copyright © 2003 O'Reilly & Associates. All rights reserved.