如何用Grep获取/dev/开头文件系统的使用率百分比?
Solution to Extract Usage Percentages for /dev/ Filesystems
Here are two reliable, straightforward ways to get the usage percentage for all filesystems starting with /dev/:
Option 1: Extending Your Original grep Approach
You can build on your existing regex by first filtering lines that start with /dev/, then extracting the numeric percentage value:
df -h | grep "^/dev/" | grep -oP "(\d+(\.\d+)?(?=%))"
Breakdown of what each part does:
df -h: Generates human-readable disk usage outputgrep "^/dev/": Filters only lines where the filesystem name starts with/dev/(the^ensures it’s matched at the start of the line)- The final
grep -oP: Extracts the numeric percentage (including optional decimals) immediately before the%sign
Option 2: Using awk (Cleaner & More Efficient)
awk lets you handle both filtering and extraction in a single command, which is often more efficient than chaining multiple greps:
df -h | awk '/^\/dev\// { sub(/%/, "", $5); print $5 }'
Breakdown:
/^\/dev\//: Matches lines starting with/dev/(we escape the/with\because it’s the delimiter for awk regex)sub(/%/, "", $5): Removes the%character from the 5th column (this is theUse%column indf -houtput)print $5: Prints the cleaned-up percentage value
Example Output
If your df -h output includes lines like:
/dev/md2 1.8T 633G 1.1T 37% / /dev/md0 976M 32M 894M 34% /boot
Both commands will output:
37 34
内容的提问来源于stack exchange,提问作者Harrison
相关产品推荐
相关产品推荐

