Sed, numbers and multiplication

Hi there.

I've used Sed to pull out some numbers, can it also be used to perform calculations on these numbers?

For example I have a text file with a list of weights however some of them are presented like 24x18g, I actually need it to multiple the two number and display it as 432g

24x18g
12x18g
300g
..
..

Many thanks

Please post a data sample

Given the lines in your original post, the following should work:

sed 'y/x/*/; s/g$//' file | bc | sed 's/$/g/'

Regards,
Alister

1 Like

AWK:

echo "24x18g
12x18g
300g" |awk -F"x" '{print NF==1?$0:$1*gensub("g","",1,$2)"g"}'
432g
216g
300g
1 Like
echo "24x18g
12x18g
300g" | awk -Fx '{$0=($1*($2?int($2):1))"g"}1'
432g
216g
300g
2 Likes

Hi Dan, thanks for you script - works great however I need it to keep the 'g' and 'Kg' characters in there, at the moment it strips them out, is there anyway with AWK to do this?

Regards

$ cat infile
24x18g
12x18g
300g
24x18Kg
12x18Kg
300Kg

$ awk -Fx '{t=$0;gsub(/[0-9x]/,"",t);$0=($1*($2?int($2):1)) t}1' infile

432g
216g
300g
432Kg
216Kg
300Kg
2 Likes