Lurch
Lurch

Reputation: 875

Converting Megabit to Kilobit in bash

I have a file out.result that contains

73.0Mb
69.7Mb
59.8Mb
71.3Mb
59.7Mb
244Kb

I need to convert the Mb values to Kb i.e

cat out.result | awk '{ total = $1 * 1000 ; print total }'

but that also does it for the value that is already in Kb

73000
69700
59800
71300
59700
244000

How do I work around this?

Upvotes: 0

Views: 144

Answers (3)

KamilCuk
KamilCuk

Reputation: 141155

Remove b and use numfmt

sed 's/b//' inputfile | numfmt --from=si --to-unit=K

Upvotes: 3

RavinderSingh13
RavinderSingh13

Reputation: 133538

With your shown samples, please try following.

awk '
{
  val=substr($0,length($0)-1)
  if(tolower(val)=="mb"){
    $0 *= 1024
  }
}
{
  print $0+0
}' Input_file

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 203674

$ awk '{print $0 * (/Mb/ ? 1000 : 1)}' file
73000
69700
59800
71300
59700
244

Upvotes: 4

Related Questions