1

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.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Rohit Sahu
  • 93
  • 1
  • 1
  • 5

5 Answers5

2

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'

Community
  • 1
  • 1
codeforester
  • 39,467
  • 16
  • 112
  • 140
1

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
Aaron
  • 24,009
  • 2
  • 33
  • 57
1

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:]]+)$ ]]
Fred
  • 6,590
  • 9
  • 20
1

I took a different approach:

echo "xres = 0: +*VGA1 1600/423x900/238+0+0  VGA1" | \
sed 's/ /\
/g' | tail -n1
Sukima
  • 9,965
  • 3
  • 46
  • 60
1

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".

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116