I want to get only let's say third line of df -h
output.
What kind of command should I use?
I want to get only let's say third line of df -h
output.
What kind of command should I use?
This will output the 3rd line, regardless of content.
df -h | sed -n 3p
The df
command actually accepts an argument identifying the filesystem you want. So you could use, for example, df /home
or df /dev/sda3
.
If you intend to parse the output for a script, you'll want to use df -P
to guarantee it never wraps to multiple lines. So, for example, you could use df -Ph /home | tail -n +2
(but if you're parsing output for a script, be aware of the possibility of filenames with spaces in them)
df /home
provides a header. You're interpreting the user's purpose. You may be right. You may be wrong, who knows?
tail -n +2
removes the header.
Jun 16, 2016 at 15:35
You can use a combination of head
and tail
:
df -h | head -3 | tail -1
Or
df -h | tail -n +3 | head -1
But note that, df
allows to filter the output from the options of df
itself, you should look at those first before using any external command.
Check man df
.
Awk is text processing tool, so it's appropriate for this task
df -h | awk 'NR == 3'
I assume you're not necessarily looking for the third line, but for the line that either mentions a specific disk (e.g. /dev/sda3
) or a specific mount point (e.g. /home
).
So instead of just displaying the third line, which is insecure because the output order might change and you might get a different result, you can filter the output by content and show only the lines that match a specific pattern or contain a keyword.
Your tool for this is grep
.
For example if you want the line about device /dev/sda3
, you type:
df -h | grep '/dev/sda3'
If you want the line mentioning your home directory as mount point, use:
df -h | grep '/home'
df -h /dev/sda3
or df -h /home
(the latter works even if it's not a mount point).
Jun 14, 2016 at 16:01
You could also use perl
:
df -h | perl -ne 'print if $.==3'
The $.
is the current line number, so you could print the Nth line with perl -ne 'print if $.==N'
.
My first idea would be a head-tail-construct.
Example:
df -h | head -3 | tail -1
head -3
causes the output to stop after three lines and tail -1
will output only the last line.
Alternatively, if you know, how the output will look like, you could also use grep
to find lines containing a certain string.