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???
1
  • 2
    Try awk. You can use it to parse out fields (i.e. columns) of output. Commented Jan 2, 2014 at 15:42

3 Answers 3

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]}
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great answer. Bonus +1 for putting the regex in a variable. Bash changed the way it does regexes between 3.1 and 3.2, so storing them in a variable gives maximum compatibility.
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)

Comments

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

1 Comment

There are several syntax errors, and you ignore the difficult part of parsing two substrings out of the result of the grep.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.