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 tworev
commands, likebut it's usually easier to use
awk
:You can do this using only shell, no external tool is needed, using Parameter Expansion:
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:]
:Example:
I personally like Florian Diesch answer. But there is this way too.
Explanation:
wc -w
gives the number of words. andcut
cuts the last wordEDIT:
I figured another way of Doing it:
Here is one using
grep
How it works:
-o
Print only the matched (non-empty) parts of a matching line.[^ ]*$
matches anything from end until it found a space.Another one liner from glenn jackman using perl