Extract X words from end of line, minus last keynumber X

The file contains one line of text followed by a number. I want to take the number X at the end, take it out and display the last X words. X is the key telling me how many words from the end that I want and X will always be less than the number of words, so no problem there.

Example input and desired output:

input: this is the file with the text 1
output: text

input: this is the file with the text 2
output: the text

input: this is the file with the text 3
output: with the text

input: this is the file with the text 4
output: file with the text

I can do this with shell and sed, but it's not elegant and there has to be a simpler solution. awk print column would be simple, except I need to go from the right side of the line instead of the left.

My quick solution, without getting into arithmetic, is to use tr to change spaces to newlines, tail -1 to extract the number, sed to get rid of the last line, then tr to change newlines back to spaces. It works fine, but now I think this will become a permanent part of the script and it's just too ugly and I'm just too braindead to figure out something different.

Try this,

$ awk '{ for(i=$NF;(NF-i)<NF;i--) { printf "%s%s",$(NF-i),FS } printf RS }'  input_file

I haven't tested all the corner cases.

Or...

 
awk '{for(i=(NF-$NF);i<NF;i++) printf (i==(NF-1))?$i "\n":$i FS}' infile

malcomex999's solution is better and straight forward.

Thanks guys. Just getting around to checking up on this. They both work.

I swear, every time I think I know a little awk, I look at something like this and it looks like Greek. I think I get it, but I wouldn't want to have to explain it to someone or I would confuse us both. I'll use malcomex999's. It still looks like Greek but it's a little shorter so it has to be better, right? :wink: