Linux 在文本文件中查找行号 - 无需打开文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12750293/
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
Find line number in a text file - without opening the file
提问by Eleco
In a very large file I need to find the position (line number) of a string, then extract the 2 lines above and below that string.
在一个非常大的文件中,我需要找到一个字符串的位置(行号),然后提取该字符串上方和下方的 2 行。
To do this right now - I launch vi, find the string, note it's line number, exit vi, then use sed to extract the lines surrounding that string.
立即执行此操作 - 我启动 vi,找到字符串,记下它的行号,退出 vi,然后使用 sed 提取该字符串周围的行。
Is there a way to streamline this process... ideally without having to run vi at all.
有没有办法简化这个过程......理想情况下根本不需要运行vi。
采纳答案by Denys Séguret
You can do
你可以做
grep -C 2 yourSearch yourFile
To send it in a file, do
要将其发送到文件中,请执行
grep -C 2 yourSearch yourFile > result.txt
回答by none
you can use cat -n
to display the line numbers and then use awk
to get the line number after a grep
in order to extract line number:
您可以使用cat -n
来显示行号,然后使用awk
获取 a 之后的行号grep
以提取行号:
cat -n FILE | grep WORD | awk '{print ;}'
although grep
already does what you mention if you give -C 2
(above/below 2 lines):
虽然grep
已经做了你提到的,如果你给-C 2
(上面/下面2行):
grep -C 2 WORD FILE
回答by squiguy
Use grep -n string file
to find the line number without opening the file.
用于grep -n string file
在不打开文件的情况下查找行号。
回答by mbarthelemy
Maybe using grep like this:
也许像这样使用grep:
grep -n -2 your_searched_for_string your_large_text_file
Will give you almost what you expect
会给你几乎你所期望的
-n : tells grep to print the line number
-n :告诉 grep 打印行号
-2 : print 2 additional lines (and the wanted string, of course)
-2 :打印另外 2 行(当然还有想要的字符串)
回答by Nelson
You can do it with grep -A
and -B
options, like this:
您可以使用 grep-A
和-B
选项来完成,如下所示:
grep -B 2 -A 2 "searchstring" | sed 3d
grep will find the line and show two lines of context before and after, later remove the third one with sed.
grep 将找到该行并显示前后两行上下文,稍后用 sed 删除第三行。