bug-coreutils
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Feature request for cut and/or sort


From: Bob Proulx
Subject: Re: Feature request for cut and/or sort
Date: Mon, 23 Jul 2007 01:12:29 +0200
User-agent: Mutt/1.5.9i

The Wanderer wrote:
> It happens not infrequently that I want to sort or cut on the final
> field of a sequence of lines which do not all have the same number of
> fields. The usual case is a list of files with full path, where I am
> interested only in the filename.

There are good alternatives to cut for this.

> The intuitive thing to do is to treat the slash as the the field
> delimiter and (taking cut as the example) cut out all but the final
> field of each line. The first part is trivial, but there does not appear
> to be any way to request the second; the field-selection syntax
> described in the cut manual invariably starts counting fields from the
> beginning of the line.

That is correct.  But cut is really not the best tool for the job.
Instead I recommend and use awk for these types of things.

  echo /path/to/somefile | awk -F/ '{print$NF}'

But there are ways to do this in the shell too.

  p=/path/to/somefile
  echo ${p##*/}

And lastly I probably should mention that the coreutils 'basename'
program does this too.

  basename /path/to/somefile

Or for as many from stdin as you want.

  find /tmp -type f -print0 | xargs -r0 -l basename

You say that you want the second from the end?  Subtract the number
from the end.

  $ echo /one/two/three/four | awk -F/ '{print$(NF-1)}'
  three

Awk is best because it is a standard utility and very stable.  But
perl and ruby are similar.  Identical to each other, amazingly.

  echo /one/two/three/four | perl -F/ -lane 'print $F[-1]'
  echo /one/two/three/four | perl -F/ -lane 'print $F[3]'

  echo /one/two/three/four | ruby -F/ -lane 'print $F[-1]'
  echo /one/two/three/four | ruby -F/ -lane 'print $F[3]'

> I would like to have a way to tell cut and sort, and for that matter
> anything else which likewise deals with fields, to count them beginning
> from the end of the line.

Nah...  Just use awk.  It is standard, portable and already does what
you ask along with many more features.  The syntax of doing this with
awk is quite obvious.  It is short and quick to type when doing it on
the command line.

Bob




reply via email to

[Prev in Thread] Current Thread [Next in Thread]