Let's say I have a file archivo
with many lines, but I only want to print one particular line, say number n
.
How can I achieve this using tools that are on a standard Linux system? The option head XX archivo | tail -N
seems impractical to me.
Let's say I have a file archivo
with many lines, but I only want to print one particular line, say number n
.
How can I achieve this using tools that are on a standard Linux system? The option head XX archivo | tail -N
seems impractical to me.
Easy to write:
Faster, especially if the line is not near the end:
A bit faster, at least if the file is large ( benchmarks ):
head … | tail …
it's much slower because the first 123465 lines go through the pipe.sed
You can do it using the (Stream Editor) command :Example:
Print the first line:
Print the seventh line:
For more information about
sed
, you can visit the official GNU documentation.Several options occur to me.
With
awk
we can say:and if the number is contained in a variable
$numero
, we can say:Since
NR
it refers to the line that is being read at a given moment, we only need to compare its value with that of the variable that we assign to it through-v linea="n"
. For example,-v linea=5
.If it turns out that the file is very, very large we can always exit after the line has been printed so as not to continue reading it unnecessarily:
If we prefer to use
sed
, we can say:And for large files:
This will print line number
N
and then stop execution.If the value is in a variable, we must use double quotes so that the value is expanded and
${n}
so that it is understood that the name of the variable is$n
and not$np
:head
andpipe
withtail
would be slow for a very large file. I would recommend usingsed
it like this:Where
NUM
is the line number you want to print.Font