Ubuntu: Is there any way to make the cut command read the last field only?


I have a space seperated string which is output by a command, which I like to pipe to cut, using -fd ' ' to split on spaces. I know I can use -f <n> to display field number <n>, but can I make it display the last field if I don't know the length of the string?

Or do I need to use a more flexible text editing tool like sed or awk?


No cut can't do that. You could use two rev commands, like

echo 'foo bar baz' | rev | cut -d' ' -f1 | rev  

but it's usually easier to use awk:

echo 'foo bar baz' | awk '{print $(NF)}'  


You can do this using only shell, no external tool is needed, using Parameter Expansion:

${var##* }  

var##* will discard everything from start up to last space from parameter (variable) var.

If the delimiter can be any whitespace e.g. space or tab, use character class [:blank:]:



$ var='foo bar spam egg'    $ echo "${var##* }"  egg      $ var=$'foo\tbar\tspam\tegg'    $ echo "$var"  foo    bar    spam    egg    $ echo "${var##*[[:blank:]]}"  egg  


I personally like Florian Diesch answer. But there is this way too.

a=$(echo "your string here" | wc -w)  echo "your string here" | cut -d' ' -f$a  


wc -w gives the number of words. and cut cuts the last word


I figured another way of Doing it:

echo "Any random string here" | tac -s' ' | head -1  


Here is one using grep

$ echo "Change is Good" | grep -o '[^ ]*$'  Good  

How it works:

  • grep with -o Print only the matched (non-empty) parts of a matching line.
  • The regexp [^ ]*$ matches anything from end until it found a space.

Another one liner from glenn jackman using perl

$ echo "Change is Good" | perl -lane 'print $F[-1]'  Good  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »