5 ms·
This is great! I always felt like cut was really handicapped by lack of negative indexes.
by bitcraft 4y ago
This is great! I always felt like cut was really handicapped by lack of negative indexes.
- tyingq 4y agoawk can do something like negative indexes if needed: $ echo "a b c" | awk '{print $(NF-1)}' b
- kseistrup 4y agoThe 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.
- layer8 4y agoI usually just pipe through sed to normalize the separators before applying cut.
- kseistrup 4y agoThat's also a little awkward, when there could easily be an option to split by all blanks.
- layer8 4y agoI’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.
- kseistrup 4y agoYou have a point, of course.
- samwhiteUK 4y agoWhen I want to use negative indices, I pipe the string through rev first, then do my cut, then rev again
- mprovost 4y agoThat's the classic solution but blows up when using multibyte characters since rev just reads the bytes in each line in reverse.
- pimlottc 4y agoWhat do you mean by negative indexes?
- ratrocket 4y agoI 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.