Rohit Sahu
Rohit Sahu

Reputation: 123

How can I extract the last field in a string?

How can I extract the last field in a string? I have a string:

xres = 0: +*VGA1 1600/423x900/238+0+0  VGA1

I want to extract the last part of the string, that is VGA1.

Upvotes: 1

Views: 743

Answers (5)

Benjamin W.
Benjamin W.

Reputation: 52536

I would use awk:

$ awk '{print $NF}' <<< 'xres = 0: +*VGA1 1600/423x900/238+0+0  VGA1'
VGA1

NF is the number of fields in the record, and $NF prints the field with number NF, i.e., the last one. Fields are by default blank separated.

Alternatively, using shell parameter expansion:

$ str='xres = 0: +*VGA1 1600/423x900/238+0+0  VGA1'
$ echo "${str##* }"
VGA1

This removes the longest matching string from the beginning, where the pattern to match is * : "anything, followed by a space".

Upvotes: 1

codeforester
codeforester

Reputation: 43109

You can use rev and cut if the string has delimiters, as in your case:

var="xres = 0: +*VGA1 1600/423x900/238+0+0  VGA1"
rev <<< "$var" | cut -f1 -d' ' | rev
# output => VGA1
  • the first rev reverses the string so that the last token shifts to the beginning, though in reverse
  • cut -f1 extracts the first field, using space as the delimiter
  • the second rev reverses the extracted field to its original state

The good thing about this solution is that it doesn't depend upon how many fields precede the last token.


Related post: How to find the last field using 'cut'

Upvotes: 2

Sukima
Sukima

Reputation: 10084

I took a different approach:

echo "xres = 0: +*VGA1 1600/423x900/238+0+0  VGA1" | \
sed 's/ /\
/g' | tail -n1

Upvotes: 1

Fred
Fred

Reputation: 7015

One way to do it with Bash builtins only (no external commands) :

var="xres = 0: +*VGA1 1600/423x900/238+0+0  VGA1"
[[ "$var" =~ [[:space:]]([^[:space:]]+)([[:space:]]*)$ ]]
match="${BASH_REMATCH[1]-}"

Please note the regular expression used will tolerate trailing whitespace in the string ; it could be simplified to avoid that if it is considered a bug rather than a feature :

[[ "$var" =~ [[:space:]]([^[:space:]]+)$ ]]

Upvotes: 1

Aaron
Aaron

Reputation: 24822

If this string always contains the same number of spaces, we can consider each space-separated part as a field and use cut to extract it :

$ echo "xres = 0: +*VGA1 1600/423x900/238+0+0  VGA1" | cut -d' ' -f7
VGA1

If that's not the case, we can use regex to match from the end, for example with grep :

$ echo "xres = 0: +*VGA1 1600/423x900/238+0+0  VGA1" | grep -o '[^ ]*$'
VGA1

Upvotes: 1

Related Questions