18

There is a sample of using the cut command to extract parts of a string starting from the left. An example is given below.

$ echo "abc-def-ghi-jkl" | cut -d- -f-2
abc-def

How can the same code be adapted to extracting from the right side? I thought of reversing the words and applying the same method, but it was too complicated.

vfclists
  • 19,193
  • 21
  • 73
  • 92

2 Answers2

31

you could use rev

echo "abc-def-ghi-jkl" | rev | cut -d- -f-2 | rev
iruvar
  • 22,736
  • 7
  • 53
  • 82
  • This is what I use. Also for `uniq -F` since it doesn't support skipping from the end – sehe Oct 12 '12 at 13:59
7
$ echo "abc-def-ghi-jkl" | cut -d- -f3-
ghi-jkl

-2 cuts up to the 2nd field. 3- cuts from the 3rd field on.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • What would the -d parameter be if they are separated by spaces – vfclists Oct 12 '12 at 13:56
  • -d\ followed by another space (so the space is a part of the parameter) – Piotr Zierhoffer Oct 12 '12 at 13:59
  • 3
    This only works if you know in advance how many fields each line will contain. – chepner Oct 12 '12 at 14:11
  • 2
    @JohnKugelman - 5 years after your answer and after revisiting it I think iruvar's answer is the better one. Given that he answered the question virtually at the same time as my comment I think it is only fair. Hopefully with over 193K ranking you shouldn't miss the points :). I had to revisit the problem today and remembered that I had a similar question on stackoverflow – vfclists Jun 13 '17 at 11:49
  • 3
    Noooooooooooooo! :'-( – John Kugelman Jun 13 '17 at 11:51