Axel
Axel

Reputation: 5111

How to convert em/rem to px?

I have a following script which converts px to em:

perl -p -i -e 's/(\d+)px/($1\/16).em/ge' stylesheet.css

However, when I tweak it to convert em to px then it doesn't work well:

perl -p -i -e 's/(\d+)em/($1*16).px/ge' stylesheet.css

It converts 2.25em to 2.400px. Please help me on this.

Upvotes: 0

Views: 287

Answers (2)

binsh
binsh

Reputation: 1

You may use a character group instead [ ]

perl -p -i -e 's/(\d[\d\.]*)px/($1\/16).em/ge'
perl -p -i -e 's/(\d[\d\.]*)em/($1*16).px/ge'

Upvotes: 0

Stefan Becker
Stefan Becker

Reputation: 5962

You are not matching the fractional part:

  • match the integer part (one or more digits `\d+)
  • match optionally a fractional part
    • match the dot (\.)
    • match the fractional part (one or more digits \d+)
$ echo '2.25em 2em' | perl -pe 's/(\d+(?:\.\d+)?)em/($1*16).px/ge'
36px 32px

Upvotes: 1

Related Questions