How to find the last field using 'cut'
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