Parse a line with a bash script to get the last element

I have a file that contains several lines of this format:

Item A               62.7         97.9              9.0
Item A B C           54.2         98.4             10.0
Another Item A       51.0         98.8              7.0
Another Item A--B--C 57.0         98.8              1.0

I would like to write a bash script that will take all the last values ​​of each line (e.g. 9.0, 10.0, 7.0 and 1.0).

The problem that I am facing is that I cannot use cut -d" " -f 4, since there are a different number of spaces in the element names. Moreover, I cannot use “more than two spaces” as a separator when used sed, because sometimes there can only be one space between the element name and the second column (for example, in the last line in the example between C and 5).

I thought that maybe I could parse every line from the end, but I'm not sure if this is doable. Any help would be appreciated as I am not very familiar with bash scripting.

thank

+3
source share
3 answers

Parsing a line from the end would be a good approach. you can usesed -e 's/^.* //'

+2
source

If you don't mind the extra comma at the end, you can do this:

 awk '{$1=$1;print $NF}' ORS="," ./infile
+3
source

If you want to get the last item in a separator, you can always change the first element of a spread list with delimiters.

echo ($LINE) | rev | cut -d" " -f1 | rev
+1
source

All Articles