How to find the last field using 'cut'
Without using sed
or awk
, only cut
, how do I get the last field when the number of fields are unknown or change with every line?
You could try something like this:
echo 'maps.google.com' | rev | cut -d'.' -f 1 | rev
Explanation
-
rev
reverses "maps.google.com" to bemoc.elgoog.spam
-
cut
uses dot (ie '.') as the delimiter, and chooses the first field, which ismoc
- lastly, we reverse it again to get
com
Use a parameter expansion. This is much more efficient than any kind of external command, cut
(or grep
) included.
data=foo,bar,baz,qux
last=${data##*,}
See BashFAQ #100 for an introduction to native string manipulation in bash.