How to find the last field using 'cut' How to find the last field using 'cut' bash bash

How to find the last field using 'cut'


You could try something like this:

echo 'maps.google.com' | rev | cut -d'.' -f 1 | rev

Explanation

  • rev reverses "maps.google.com" to be moc.elgoog.spam
  • cut uses dot (ie '.') as the delimiter, and chooses the first field, which is moc
  • 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,quxlast=${data##*,}

See BashFAQ #100 for an introduction to native string manipulation in bash.


It is not possible using just cut. Here is a way using grep:

grep -o '[^,]*$'

Replace the comma for other delimiters.

Explanation:

  • -o (--only-matching) only outputs the part of the input that matches the pattern (the default is to print the entire line if it contains a match).
  • [^,] is a character class that matches any character other than a comma.
  • * matches the preceding pattern zero or more time, so [^,]* matches zero or more non‑comma characters.
  • $ matches the end of the string.
  • Putting this together, the pattern matches zero or more non-comma characters at the end of the string.
  • When there are multiple possible matches, grep prefers the one that starts earliest. So the entire last field will be matched.

Full example:

If we have a file called data.csv containing

one,two,threefoo,bar

then grep -o '[^,]*$' < data.csv will output

threebar