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?
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
从第 5 行开始显示:
awk 'NR>4' file
sed -n '3,$p' file
这只是填充文本,因为 stackoverflow 不喜欢短命令行。
打印,但删除第 1 到 2 行:
sed '1,2d' filename
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. 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 -vn=${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'
:-)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.