Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Last n words from a string in bash

Tags:

string

bash

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.

like image 878
user1418018 Avatar asked Dec 18 '25 17:12

user1418018


1 Answers

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
like image 64
fedorqui 'SO stop harming' Avatar answered Dec 20 '25 10:12

fedorqui 'SO stop harming'



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!