Hacker News new | ask | show | jobs
by bitcraft 1468 days ago
This is great! I always felt like cut was really handicapped by lack of negative indexes.
4 comments

The biggest handicap of cut for me has always been that it cannot split on blanks (TABs or SPACEs), you have to choose between TAB or SPACE. So I wrote an awk script that can print field ranges like cut, but recognizes blanks. Now I will see if I can get tuc worked into my muscle memory.
I usually just pipe through sed to normalize the separators before applying cut.
That's also a little awkward, when there could easily be an option to split by all blanks.
I’m not defending cut here, but using sed is also pretty straightforward and fits its purpose. I’d argue that using the existing general-purpose tools is better than creating custom narrow-purpose tools in simple cases like this one. Besides maintainability and familiarity, it also exercises your proficiency in applying the standard tools.
You have a point, of course.
awk can do something like negative indexes if needed:

  $ echo "a b c" | awk '{print $(NF-1)}'
  b
When I want to use negative indices, I pipe the string through rev first, then do my cut, then rev again
That's the classic solution but blows up when using multibyte characters since rev just reads the bytes in each line in reverse.
What do you mean by negative indexes?
I believe "negative index" means array[-1] is the last element in array, array[-2] is the second-to-last element, etc.

In the context of "cut", it would mean being able to do something like:

cut -d" " -f1--2

the "-f1--2" (read: fields from 1 to minus 2; it's a range) means to select from the first field to the second-to-last field. (that double "--" is pretty awkward, to be sure!)

Some programming languages (ruby is the one that I know) have this feature for accessing array elements.