简体   繁体   中英

How can I make this bash code remove the decimal places?

free | grep Mem | awk '{print $4/$2 * 100.0}'

I want to remove the decimal places from this output.

free | grep Mem | awk '{print $4/$2 * 100.0}' | cut -d. -f1

or

free | grep Mem | awk '{print int($4/$2 * 100.0)}'

A couple observations:

  1. No need for using grep as awk can handle that
  2. Use printf instead of print to control the precision
free | awk '/Mem/ { percent = $4 / $2 * 100.0; printf "%0.0f\n", percent; }'
  1. Use awk /pattern/ to select the correct row.
  2. Convert to integer to get rid of decimal points.

Code:

free | awk '/Mem/ { print int(100 * $4 / $2) }'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM