Search code examples
awksedcut

print last two words of last line


I have a script which returns few lines of output and I am trying to print the last two words of the last line (irrespective of number of lines in the output)

$ ./test.sh

service is running..
check are getting done
status is now open..
the test is passed

I tried running as below but it prints last word of each line.

$ ./test.sh |  awk '{ print $NF }'

running..
done
open..
passed

how do I print the last two words "is passed" using awk or sed?


Solution

  • Just say:

    awk 'END {print $(NF-1), $NF}'
    

    "normal" awks store the last line (but not all of them!), so that it is still accessible by the time you reach the END block.

    Then, it is a matter of printing the penultimate and the last one. This can be done using the NF-1 and NF trick.