Subject: Re: bug#22128: dirname enhancement

From: Bob Proulx <[email-masked]>
Date: Thu, 10 Dec 2015 10:40:30 -0700

Nellis, Kenneth wrote:
> Still, my -f suggestion would be easier to type,
> but I welcome your alternatives.

Here is the problem.  You would like dirname to read a list from a
file.  Someone else will want it to read a file list of files listing
files.  Another will want to skip one header line.  Another will want
to skip multiple header lines.  Another will want the exact same
feature in basename too.  Another will want file name modification so
that it can be used to rename directories.  And on and on and on.
Trying to put every possible combination of feature into every utility
leads to unmanageable code bloat.

What do all of those have in common?  They are all specific features
that are easily available by using the features of the operating
system.  That is the entire point of a Unix-like operating system.  It
already has all of the tools needed.  You tell it what you want it to
do using those features.  That is the way the operating system is
designed.  Utilities such as dirname are simply small pieces in the
complete solution.

In this instance the first thing I thought of when I read your dirname
-f request was a loop.

   while read dir; do dirname $dir; done < list

Pádraig suggested xargs which was even shorter.

  xargs dirname < filename

Both of those directly do exactly what you had asked to do.  The
technique works not only with dirname but with every other command on
the system too.  A technique that works with everything is much better
than something that only works in one small place.

Want to get the basename instead?

   while read dir; do basename $dir; done < list

Want to modify the result to add a suffix?

   while read dir; do echo $dir.myaddedsuffix; done < list

Want to modify the name in some custom way?

   while read dir; do echo $dir | sed 's/foo/bar/; done < list

Want a sorted unique list modified in some custom way?

   while read dir; do echo $dir | sed 's/foo/bar/'; done < list | sort -u

The possibilities are endless and as they say limited only by your
imagination.  Anything you can think of doing you can tell the system
to do it for you.  Truly a marvelous thing to be so empowered.

Note that in order to be completely general and work with arbitrary
names that have embedded newlines then proper quoting is required and
the wisdom of today says always use null terminated strings.  But if
you are using a file of names then I assume you are operating on a
restricted and sane set of characters so this won't matter to you.
I do that all of the time.

Bob