Somethingwhatever
Somethingwhatever

Reputation: 1348

Awk get specific line?

I am trying to get a specific line using awk command.

When i do df -h, i get :-

Filesystem      Size  Used Avail Use% Mounted on
udev             16G     0   16G   0% /dev
tmpfs           3.2G  2.7M  3.2G   1% /run
/dev/nvme0n1p2  468G   64G  381G  15% /
tmpfs            16G   77M   16G   1% /dev/shm
tmpfs           5.0M  4.0K  5.0M   1% /run/lock
tmpfs            16G     0   16G   0% /sys/fs/cgroup
/dev/loop0      100M  100M     0 100% /snap/core/11420
/dev/loop2       56M   56M     0 100% /snap/core18/2074

Using df -h | awk '{print $2, $3, $4, $5}' gives me the following output :-

Size Used Avail Use%
16G 0 16G 0%
3.2G 2.7M 3.2G 1%
468G 64G 381G 15%
16G 80M 16G 1%
5.0M 4.0K 5.0M 1%
16G 0 16G 0%

How can i only get the contents from anything associated with "/" partition whether only using awk or maybe some other command?

Upvotes: 3

Views: 1406

Answers (3)

You can use the slash sign in a regular expression before the awk print statement:

df -h | awk '$6 ~ /\// {print $2, $3, $4, $5}'

Upvotes: 0

David C. Rankin
David C. Rankin

Reputation: 84561

A very simple alternative using sed simply suppresses normal printing of pattern-space with -n and outputs the line ending in '/', e.g.

df -h | sed -n '/\/$/p'

If you want to squeeze the whitespace between each field of output to a single whitespace delimiter, you can simply pipe to tr, e.g.

df -h | sed -n '/\/$/p' | tr -s [[:blank:]]

Example Use/Output

With your df output in the file dat/dfout.txt, you would have:

$ sed -n '/\/$/p' dat/dfout.txt
/dev/nvme0n1p2  468G   64G  381G  15% /

Or on my system with the whitespace between each field squeezed to a single whitespace, you have:

$ df -h | sed -n '/\/$/p' | tr -s [[:blank:]]
/dev/sdb2 40G 31G 6.5G 83% /

With awk and a REGEX

Another trivial way using awk is using a regex match for the same '/' at the end, e.g.

df -h | awk '$6 ~ /\/$/'

(the default rule print is applied on match)

The same thing squeezing the whitespace to a single delimiter would be:

df -h | awk '$6 ~ /\/$/ {$1 = $1; print}'

Where $1 = $1 forces the fields to be recalculated removing excess whitespace, but then an explicit print is needed as more than the default rule is provided.

Upvotes: 0

jhnc
jhnc

Reputation: 16752

One awk way would be to filter on field 6. Perhaps:

df -h | awk '$6=="/" {print $2, $3, $4, $5}'

Alternatively, you could tell df to only show /:

df -h / | awk '{print $2, $3, $4, $5}'

Upvotes: 4

Related Questions