Robert
Robert

Reputation: 38213

How do I use grep to parse a portion of bash command output into a variable?

$ file myImage.png

Produces this result:

myImage.png: PNG image data, 42 x 64, 8-bit grayscale, non-interlaced

I want to parse the width and the height into variables, something like this:

MY_WIDTH  = file myImage.png | grep ???x
MY_HEIGHT = file myImage.png | grep x???

Upvotes: 2

Views: 344

Answers (3)

Anders Lindahl
Anders Lindahl

Reputation: 42870

If you are indeed interested in the resolution of an image, there are better utilities than file in the imagemagick package. Specifically the identify tool:

MY_WIDTH=$(identify -format "%w" myImage.png)
MY_HEIGHT=$(identify -format "%h" myImage.png)

Upvotes: 4

LOGMD
LOGMD

Reputation: 249

I beleive you will need a regular expression that detects the ' x ' pattern with the numbers on either side.

This thread may help you start as it says:

xrandr|grep -Po '\d+(?=\s*x.*\*.*)'

instead you could do

RES = file myImage.png ||grep -Po '\d+(?=\s*x.*\*.*)'

then modify accordingly to seperate the two into your variables

Upvotes: 0

chepner
chepner

Reputation: 530922

You can use subgroup capturing with a regular expression match:

regex='([0-9]+) x ([0-9]+)'
[[ $(file myImage.png) =~ $regex ]] && {
    MY_WIDTH=${BASH_REMATCH[1]}
    MY_HEIGHT=${BASH_REMATCH[2]}
}

Upvotes: 5

Related Questions