views:

182

answers:

4
+1  Q: 

sed calculations

Hi.

I want to parse a css file and multiply each pixel value by (2/3). I was wondering if this was possible with sed? I know this is incorrect syntax but i think it'll bring home the explanation of what i want to achieve:

sed -e "s|\([0-9]*\)px|int((\1 * 2)/3)|g" file.css

So basically I want to take \1, multiply it by (2/3) and cast to and int. Or maybe it's more possible with awk? Suppose I could write a python script, but would like to know if it can be done by quicker means.

Thanks

A: 

You can use perl do it like this:

echo -e "100px;\n20px;" | perl -pe 's{ (\d*) (?=px) }{ $1*(2/3) }xe'
ar
+3  A: 

use awk

$ cat file
foo: 3px; bar: 6px

$ awk '{for(i=1;i<=NF;i++){if($i~/^[0-9]+px/){o=$i;sub(/^[0-9]+/,"",o);$i=($i+0)*(2/3)o}}}1' file
foo: 2px; bar: 4px
ghostdog74
It doesn't work on `foo:3px`, which *is* valid CSS. But as long as you don't write junk like that, you're fine :D @tomh `-vCONVFMT=%d` will make sure the numbers are truncated to integers.
ephemient
A: 

Thanks for the replies.

@ghostdog74: Thanks, that's pretty much it. Just need to wrap that in a function to round off the decimals.

tomh
This should be a comment, not an answer. Please delete this and use the "add comment" under the relevant post to post your comments rather than posting as if it was a traditional forum.
Mehrdad Afshari
A: 

To answer the initial question: Yes, you can do this in sed, and No, you do NOT want to do it unless you have some bizarre set of constraints that prevent you from using any other tool.

I say this because the unix dc command (a desktop calculator) has been written in sed, but it works IIRC by performing math the same way you were probably taught math in school: string manipulations on digits, along with carries and such.

You would actually have to write multiply and divide commands (or strip them out of dc.sed) to be able to accomplish this and the results would run a couple of orders of magnitude slower than any of the above suggestions.

In case you're now curious about dc.sed, its usually provided as one of the examples in any sed distribution.

swestrup
Overview: http://sed.sourceforge.net/grabbag/scripts/dc_overview.htm Script: http://sed.sourceforge.net/grabbag/scripts/dc.sed
Dennis Williamson