开发者

Parse string with bash script to get last item

开发者 https://www.devze.com 2023-02-16 05:31 出处:网络
I have a file which contains multiple lines of this format: Item A62.797.99.0 Item A B C54.298.410.0 Another Item A51.098.87.0

I have a file which contains multiple 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 would take all the last values of each line, (e.g. 9.0, 10.0, 7.0, and 1.0).

The problem that I am encountering is that I can't use cut -d" " -f 4 since there are different number of spaces in the item names. Moreover, I cannot use 'more than 2 spaces' as a delimiter when using sed since sometimes there would be only one space between the item name and the second column (like in the last line in the example, between C and 5).

I thought m开发者_高级运维aybe I could parse each line from the end, but I am not sure if that is doable. Any help will be appreciated, as I am not very familiar with bash scripting.

Thank you


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

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


Parsing the line from the end would be a good approach here. You could use sed -e 's/^.* //'


If you're looking to get the last item in a delimited, you can always reverse the first item of a reversal of the delimited list.

echo ($LINE) | rev | cut -d" " -f1 | rev
0

精彩评论

暂无评论...
验证码 换一张
取 消