How to find the last field using 'cut'
Without awk ?... But it's so simple with awk:
echo 'maps.google.com' | awk -F. '{print $NF}'
AWK is a way more powerful tool to have in your pocket. -F if for field separator NF is the number of fields (also stands for the index of the last)
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
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,three
foo,bar
then grep -o '[^,]*$' < data.csv
will output
three
bar
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.