Ambidex
Ambidex

Reputation: 857

How to capture digits in front of specific keyword in bash

Imagine following string:

<tr><td>12,3</td><td>deg</td><td>23,4</td><td>humi</td><td>34,5</td><td>press</td></tr>

In bash, how do I extract 23.4, based on the condition that it is followed by humi?

Upvotes: 0

Views: 38

Answers (1)

GKFX
GKFX

Reputation: 1400

grep -o works well for this sort of thing. I'm sure performance would be better with a single sed command than two greps but that's rarely a serious concern.

X='<tr><td>12,3</td><td>deg</td><td>23,4</td><td>humi</td><td>34,5</td><td>press</td></tr>'
echo $X | grep -o '[0-9,.]*</td><td>humi' | grep -o '[0-9,.]*'
# Result: 23,4

You can additionally pipe through tr , . to get English number format.

Upvotes: 1

Related Questions