Ubuntu – How to get a substring from bash command

bashcommand line

Given the following substring given obtained from the command df /dev/sdb1 | tail -n 1 :

/dev/sdb1 1952971772 1441131032 511840740 74% /media/kaiman/ShareData

I'd like to extract 1952971772 and 74% from that string, to use it in a bash script.

I know I could use some cut commands or something, but it won't work anymore if a size changes, for example.

I also had thoughts about using a regex or something, but I'd like to have the most recommended approach.

Thanks in advance!

Best Answer

$ 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.

Related Question