da4
da4

Reputation: 167

Better awk formatting

So I have some output, like so:

   Total Size:               999.4 GB (999360274432 Bytes) (exactly 1951875536 512-Byte-Units)
   Volume Free Space:        320.4 GB (320392282112 Bytes) (exactly 625766176 512-Byte-Units)

And I'd like to awk it to:

Total Size: 999.4 GB
Free Space: 320.4 GB

But using awk '{ print $1 " " $2 " " $3 " " $4 }' removes the second 'GB' since the first line has four fields to return, the second line has five.

I know there must be a better, more awk-ish way than using substr:

awk '{ print substr( $0, 0, 37 ) }'

(which gets me close).

Or should I be using sed?

Upvotes: 1

Views: 86

Answers (2)

John1024
John1024

Reputation: 113994

This works by changing the field separator to : or (:

$ awk -F'[:(]' '{ print $1":"$2 }' file
Total Size:               999.4 GB 
Volume Free Space:        320.4 GB 

If you want to remove Volume:

$ awk -F' *[:(] *' '{ sub(/^ *(Volume)? */, ""); printf "%-10s: %s\n",$1,$2 }' file
Total Size: 999.4 GB
Free Space: 320.4 GB

The above will need to be altered if your input has not just spaces but also tabs. In that case:

$ awk -F' *[:(][[:space:]]*' '{ sub(/^[[:space:]]*(Volume)?[[:space:]]*/, ""); printf "%-10s: %s\n",$1,$2 }' file
Total Size: 999.4 GB
Free Space: 320.4 GB

Addendum: calculating percent free space

$ awk -F' *[:(][[:space:]]*' '/Size/{s=$2} /Free/{f=$2} END{ printf "Total Size: %s\nFree Space: %s\nRatio:      %s%%\n",s,f,100*f/s }' file
Total Size: 999.4 GB
Free Space: 320.4 GB
Ratio:      32.0592%

Upvotes: 4

ritter
ritter

Reputation: 597

Tell awk to use a different field separator. In this instance, you have a colon that separates your text from the values. In effect, the colon becomes your field separator:

cat <content> | awk -F: '{ print $1 $2 }'

Then field $1 contains the leading text, while field $2 contains everything after.

Upvotes: 0

Related Questions