Reputation: 451
I want to display all the lines starting from the nth line. Say, print the third line of a file and all the following lines until end of file. Is there a command for that?
Upvotes: 44
Views: 65547
Reputation: 16362
You can use sed
:
sed -n '3,$p' file
This selects line 3 to the end and prints it.
Upvotes: 16
Reputation: 881163
The awk
command can do this by only printing lines to the NR
record number is three or more:
awk 'NR>=3' input_file_name
You can also pass the value into awk
using a variable if need be:
awk -v n=3 'NR>=n' input_file_name
(and you can use -v n=${num}
to use an environment variable as well).
There are many other tools you can use to do the same job, tail
, sed
and perl
among them or, since this is a programming Q&A site, just roll your own:
#include <stdio.h>
int main (void) {
// Need character and # of newlines to skip.
int ch, newlines = 2;
// Loop until EOF or first lines skipped, exit on EOF.
while ((ch = getchar()) != EOF)
if ((ch == '\n') && (--newlines == 0))
break;
if (ch == EOF)
return 0;
// Now just echo all other characters, then return.
while ((ch = getchar()) != EOF)
putchar (ch);
return 0;
}
Now you wouldn't normally write your own filter program for this but, since you asked for the shortest command, you could use that source code to create an executable called x
to do it:
x <input_file_name
You'd be hard-pressed finding a shorter command than that. Of course, assuming you're in a UNIXy environment (specifically, bash
), you could also just:
alias x awk 'NR>=3'
:-)
Upvotes: 4
Reputation: 3646
You can use awk
like this:
awk 'BEGIN{n=5}NR<=n{next}1' file
BEGIN{n=5}
- before file processing starts, sets n
to the number of lines to skip (5).NR<=n{next}
- skips processing if the line number is less than or equal to n
.1
- shorthand for print
everything else.Upvotes: 5
Reputation: 20124
you can use tail
excerpt from the manpage:
-n, --lines=K output the last K lines, instead of the last 10; or use -n +K to output lines starting with the Kth
for example
tail -n +10 file
outputs the files content starting with the 10th line
Upvotes: 69