bash 在 Linux 中打印文件的第 3、4 和 5 行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22542514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Print 3, 4 and 5 line of the file in Linux
提问by pw94
I have a problem with a Linux command. I have to put on the output 3, 4 and 5 line of the file /etc/passwd, but I have no idea how to do it. I can print first five line:
我的 Linux 命令有问题。我必须在文件/etc/passwd的输出 3、4 和 5 行上加上,但我不知道该怎么做。我可以打印前五行:
head -n 5 /etc/passwd
but I don't know how to remove first two lines or do all from scratch.
但我不知道如何删除前两行或从头开始。
回答by devnull
Using sed
:
使用sed
:
sed -n '3,5p' /etc/passwd
or
或者
sed -n '3,5p;6q' /etc/passwd
(The second version would quit upon encountering line 6 so it would be efficient for huge files.)
(第二个版本会在遇到第 6 行时退出,因此它对于大文件很有效。)
Using awk
:
使用awk
:
awk 'NR==3,NR==5' /etc/passwd
or
或者
awk 'NR>=3{print}NR==5{exit}' /etc/passwd
(The second variant quit after printing line 5 so it's more efficient.)
(第二个变体在打印第 5 行后退出,因此效率更高。)
Using perl
:
使用perl
:
perl -ne 'print if $.>=3 and $.<=5;' /etc/passwd
or
或者
perl -ne 'print if $.>=3; last if $.>5' /etc/passwd
(The second variant is, again, more efficient.)
(同样,第二个变体更有效。)
For fun, lets time these different approaches on an input of 10 million lines:
为了好玩,让我们在 1000 万行的输入上计时这些不同的方法:
$ time seq 10000000 | sed -n '3,5p'
3
4
5
real 0m10.086s
user 0m9.173s
sys 0m0.101s
$ time seq 10000000 | sed -n '3,5p;6q'
3
4
5
real 0m0.012s
user 0m0.010s
sys 0m0.001s
$ time seq 10000000 | awk 'NR==3,NR==5'
3
4
5
real 0m12.906s
user 0m11.475s
sys 0m0.134s
$ time seq 10000000 | awk 'NR>=3{print}NR==5{exit}'
3
4
5
real 0m0.013s
user 0m0.001s
sys 0m0.010s
$ time seq 10000000 | perl -ne 'print if $.>=3 and $.<=5;'
3
4
5
real 0m15.982s
user 0m14.217s
sys 0m0.179s
$ time seq 10000000 | perl -ne 'print if $.>=3; last if $.>5'
3
4
5
6
real 0m0.013s
user 0m0.000s
sys 0m0.011s
It's evident that quitting in case of large inputs once the desired lines are obtained is much more efficient. On small inputs, the difference would be negligible, though.
很明显,一旦获得所需的行,在大量输入的情况下退出会更有效率。不过,在小投入上,差异可以忽略不计。
回答by rekire
Use tail:
使用尾巴:
head -n 5 /etc/passwd | tail -n 3
Tail returns the last lines of a file together with a pipe you can use both features.
Tail 返回文件的最后几行以及可以使用这两个功能的管道。