1

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. :)

curtis
  • 184
  • 1
  • 7
  • How about awk? `cat text | awk '/^virtual size/ {gsub(/.*\(/,""); gsub(/ bytes.*/,"");print}'`. Find the line matching 'virtual size', replace everything before the '(', replace everything after the ' bytes). – Zoredache Jun 04 '13 at 21:53

4 Answers4

1

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.

Brigo
  • 1,534
  • 11
  • 8
1
echo "virtual size: 40G (42949672960 bytes)" | grep -Po '(?<=\()[^ ]*'

Match on the left (the right matches to the space

echo "virtual size: 40G (42949672960 bytes)" |grep -oP 'virtual.*\K(?<=\()[^ ]*'

Or a more rigorous match to start with the text beginning with virtual

hepha
  • 11
  • 3
1
qemu-img ... | grep -Po '[0-9]+(?= bytes)'

This is using a zero-length lookahead assertion, which will match the bytes text but won't include it in the output (because the -o option was given).

Such assertions are available when the -P switch to grep is used (which directs it to use perl/pcre-like regex'es). Both -P and -o were already used in OP's question and in the title.

0

echo "virtual size: 40G (42949672960 bytes)" | grep -Po '(\K([^\s]+)'

atareao
  • 101
  • 1