I have a string containing many (the total number varies) words, and I need to get last 10 of them. How do I do it? I'm looking at awk, grep and cut but nothing really comes to mind.
An example (although it seems to me that the question is clear):
aaa bda fdkfj fds fsd ... dsad dsas dsad zrthd shshh
I want the last 10 words of this string.
Again, the total number of words in the initial string isn't defined.
Just play with tr, tail and xargs:
$ echo "1 2 3 4 5 6 7 8 9 10" | tr ' ' '\n' | tail -5 | xargs -n5
6 7 8 9 10
This prints the words one in every line, so that tail gets the desired amount of them. Then, xargs "remerges" them in the same line.
You can also set awk's NF to the value you want after reversing the text:
$ echo "1 2 3 4 5 6 7 8 9 10" | rev | awk '{NF=5}1' | rev
6 7 8 9 10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With