How to get a substring from bash command

Solution 1:

Edited answer

As @kevin stated, you can use awk to select only the last line and avoid using tail at all by using END and also if you want to print two columns at once you can do this:

df /dev/sdb1 | awk 'END {print $2,$5}'
1952971772 74%

Original answer

You can select the 2nd columns only:

$ df /dev/sdb1 | tail -1 | awk '{print $2}' 
1952971772

Where $2 indicates the position of TAB separated columns. You can use cut because it handle only one occurrence of TAB and here there are multiples TABs to delimita a column.

Solution 2:

$ df /dev/sdb1 | awk '{ print $5 }' | tail -n 1

for the percentage and

$ df /dev/sdb1 | awk '{ print $2 }' | tail -n 1

for the size.

Without the tail:

df /home | awk 'NR==2 { print $2 }'
df /home | awk 'NR==2 { print $5 }'

  • awk '{ print $2 }'
    gets the 2nd column where multiple separators count as 1. So the 2nd column is always the same for your system for the 1st part of the command.

  • NR gives you the total number of records being processed or the line number.