2
$ 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???
Robert
  • 37,670
  • 37
  • 171
  • 213

3 Answers3

5

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]}
}
chepner
  • 497,756
  • 71
  • 530
  • 681
  • 2
    Great answer. Bonus +1 for putting the regex in a variable. Bash changed the way it does regexes [between 3.1 and 3.2](http://stackoverflow.com/questions/218156/bash-regex-with-quotes), so storing them in a variable gives maximum compatibility. – John Kugelman Jan 02 '14 at 15:48
4

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)
Anders Lindahl
  • 41,582
  • 9
  • 89
  • 93
0

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

Community
  • 1
  • 1
LOGMD
  • 239
  • 2
  • 16
  • 1
    There are several syntax errors, and you ignore the difficult part of parsing two substrings out of the result of the `grep`. – chepner Jan 02 '14 at 15:50