convert string KB/MB/GB values

gormenghast
gormenghast used Ask the Experts™
on
Hi,

I want to process strings within a ksh script similar to this ...

07/17/09 15:55:00 74 10G 9968M 31% 27%

and convert fields with a "G" "M" or "K" value to a KB value with no suffix.
ie convert the example string to ...

07/17/09 15:55:00 74 10485760 10207232 31% 27%

Is there a simple way to do this using sed and/or awk?

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2014
Top Expert 2015
Commented:
echo 07/17/09 15:55:00 74 10G 9968M 31% 27% | awk '{ while( match($0,/[0-9]+M/) ){ $0=substr($0,1,RSTART) (substr($0,RSTART,RLENGTH-1)*1024) substr($0,RSTART+RLENGTH); }while( match($0,/[0-9]+G/) ){ $0=substr($0,1,RSTART) (substr($0,RSTART,RLENGTH-1)*1024*1024) substr($0,RSTART+RLENGTH); } }1'
Top Expert 2015

Commented:
If you do not pass -h parameter to df which generates this output you get sizes in disk blocks.

Author

Commented:
ozo,
It looks good but i am having trouble spotting the syntax error...

# ksh -x sn
+ awk { while( match($0,/[0-9]+M/) ){ $0=substr($0,1,RSTART) (substr($0,RSTART,RLENGTH-1)*1024) substr($0,RSTART+RLENGTH); }while( match($0,/[0-9]+G/) ){ $0=substr($0,1,RSTART) (substr($0,RSTART,RLENGTH-1)*1024*1024) substr($0,RSTART+RLENGTH); } }1
+ echo 07/17/09 15:55:00 74 10G 9968M 31% 27%
awk: syntax error near line 1
awk: illegal statement near line 1
awk: syntax error near line 1
awk: bailing out near line 1
Expert Spotlight: Joe Anderson (DatabaseMX)

We’ve posted a new Expert Spotlight!  Joe Anderson (DatabaseMX) has been on Experts Exchange since 2006. Learn more about this database architect, guitar aficionado, and Microsoft MVP.

ozo
Most Valuable Expert 2014
Top Expert 2015

Commented:
what version of awk are you using?
can you try it it with gawk or nawk?
echo 07/17/09 15:55:00 74 10G 9968M 31% 27% | awk '{ gsub("G","MM"); while( match($0,"[0-9]+M") ){ $0=substr($0,1,RSTART) (substr($0,RSTART,RLENGTH-1)*1024) substr($0,RSTART+RLENGTH); }}1'

Author

Commented:
sorted ...
# ksh -x sn
+ nawk { while( match($0,/[0-9]+M/) ){ $0=substr($0,1,RSTART) (substr($0,RSTART,RLENGTH-1)*1024) substr($0,RSTART+RLENGTH); }while( match($0,/[0-9]+G/) ){ $0=substr($0,1,RSTART) (substr($0,RSTART,RLENGTH-1)*1024*1024) substr($0,RSTART+RLENGTH); } }1
+ echo 07/17/09 15:55:00 74 10G 9968M 31% 27%
07/17/09 15:55:00 74 110485760 910207232 31% 27%

thanks ozo - top solution as always
Top Expert 2015

Commented:
How do you know when G is 1024x1024x1024 and when it is 1000x1000x1000 ? kind of 7% difference but who cares less...

Author

Commented:
1Gb is 1024Mb
1Mb is 1024Kb

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial