命令行 - 显示文件中已知确切行号周围的上下文行
如何在文件中输出围绕特定已知线号(例如5)的n(例如2)行?
cat >/tmp/file <<EOL
foo
bar
baz
qux
quux
EOL
# some command
预期输出:
bar
baz
qux
How to output N(e.g. 2) lines surrounding a specific known line number(e.g. 5) in a file?
cat >/tmp/file <<EOL
foo
bar
baz
qux
quux
EOL
# some command
Expected output:
bar
baz
qux
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您提前知道行和行数,因此您可以计算可能使用简单GNU
sed
命令的第一行和最后一行的数量,例如,将输出3rd ,
file.txt
的第四,第五,第六和第7行。如果您想更改行号,那么我将使用gnu
awk
以下方式说明:我将n设置为5,然后我使用 range 从
n-2
th行(包含> n+2 TH行(包含),没有提供任何措施,这等效于{print}
。If you know the line and number of lines in advance and thus you are able to compute the number of the first line and number of the last line you might use simple GNU
sed
command, for examplewill output 3rd, 4th, 5th, 6th and 7th line of
file.txt
.If you wish to change the line number then I would use GNU
AWK
following wayExplanation: I set n to 5 then I use Range to select lines from
n-2
th line (inclusive) ton+2
th line (inclusive), no action is provided which is equivalent of giving{print}
.稳健、可移植且高效地打印上下文(目标行两侧的行数相同):
或目标行前后的行数不同:
特别是为了提高效率注意:
NR==end{exit}
而不是NR==end{f=0}
或类似的所以 awk 不会浪费在打印所需的行后,不必要地读取输入文件的其余部分。Robustly, portably, and efficiently printing a context (same number of lines either side of a target line):
or different numbers of lines before and after the target line:
In particular for efficiency note:
NR==end{exit}
instead ofNR==end{f=0}
or similar so awk doesn't waste time unnecessarily reading the rest of the input file after the desired lines have been printed.不带行号前缀:
带行号前缀:
Without line number prefixes:
With line number prefixes:
这可能对您有用(gnu sed and bash):
从文件的第5行获取范围+/- 2行。
另一种方法是使用GREP:
使用SED中的文件中的第5行,然后GREP 2行上下文的两条线。
This might work for you (GNU sed and bash):
Which fetches the range +/- 2 lines from line 5 of file.
Another way is to use grep:
Find line 5 in file using sed and then grep 2 lines of context either side of that line.