Search code examples
linuxshellcut

Use cut in shell to extract last word


I am using Red Hat linux.

I have a file foo.txt which reads

Hello world I am foo

I want to get the last word which is foo when I do cat

I tried seeing a few posts here which explained to use cut command but its very confusing. Can somebody help me getting this right?

I am looking for a command which migh go something like below

cat foo.txt | cut <the options to get the last word /or last 3 characters>

Solution

  • cut can't count from the right. But you can use rev to reverse each line, than count from the left normally, and revert the line back. It's still surprisingly fast.

    rev foo.txt | cut -d' ' -f1 | rev
    
    • -d specifies the delimiter, I guess you want spaces when counting words
    • -f specifies which field(s) to extract. Use -c to extract individual characters.