How to match (whitespace digits whitespace) sequence?

Hi

Following is an example line.

echo "192.22.22.22 [23ddddd] \"33dffwef\" 200 300 dsdsd"  | sed "s:\(\ [0-9]*\ \):\1:"

I want it's output to be

200

However this is not the case. Can you tell me how to do it? I don't want to use AWK for this. Secondly, how can i fetch just 300? Should I use "\2" for that?

When i use the following code

echo "192.22.22.22 [23ddddd] \"33dffwef\" 200 300 dsdsd"  | sed "s:\(\ [0-9]*\ \):TEST:"

200 gets replaced by TEST. If it can MATCH 200, why is it not showing it?

Thanks in advance.

It is showing! However you don't see it as such.

Let's analyze it:

sed "s:\(\ [0-9]*\ \):\1:"

It matches space200space and encapsulates it, right?

sed "s:\(\ [0-9]*\ \):\1:"

It replaces it with what it was encapsulated, as TEST proved it. Nevertheless, since 200 is replaced by 200, you don't think it did.

You have to match the whole and disregard what you don't want.

echo "192.22.22.22 [23ddddd] \"33dffwef\" 200 300 dsdsd"  | sed "s:.*\(\ [0-9]*\ \)[0-9].*:\1:"

That matches the space200space.
If you want space300space

echo "192.22.22.22 [23ddddd] \"33dffwef\" 200 300 dsdsd"  | sed "s:.*\(\ [0-9]*\ \).*:\1:"

Removing the [0-9] will do it, because of the greedy nature of the first .*

1 Like

Thanks a lot. And I was trying for such a long time to select what I want :slight_smile:

$ echo "192.22.22.22 [23ddddd] \"33dffwef\" 200 300 dsdsd" | awk '{print $5}'
300
$ echo "192.22.22.22 [23ddddd] \"33dffwef\" 200 300 dsdsd" | awk '{print $4}'
200