Using grep -Po to extract regex

grep

I've been struggling with "grep -Po" off and on for a couple hours.

What I would like to do is to find out how many bytes the virtual disk size is as reported by qemu-img info.

Here's example output:

$ qemu-img info 022eb199-954d-4c78-8550-0ea1d31111ec                                           
image: 022eb199-954d-4c78-8550-0ea1d31111ec
file format: qcow2
virtual size: 40G (42949672960 bytes)
disk size: 20G
cluster_size: 65536

And here's what I've been trying variations of:

$ qemu-img info 022eb199-954d-4c78-8550-0ea1d31111ec | grep -Po '\(([0-9]+).*\)'
(42949672960 bytes)

But I would just like the number. I guess I'm struggling with how to tell "grep -Po" which part of the regex I'd like extracted. I thought the "(" brackets would do that.

Any help would be greatly appreciated. 🙂

Best Answer

You can use cut twice, for example:

echo "virtual size: 40G (42949672960 bytes)"| cut -f 4 -d" "| cut -c 2-

First cut cuts (42949672960,-f4 fourth field, -d" " is the separator. The second cut cuts 42949672960 -c2- (cuts from second character to the end.

Related Topic