Linux 如何在指定的行号后grep字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13109580/
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
How to grep a string after a specified line number?
提问by alwbtc
I have a large text file, I want to see the lines containing "time spent"in this text file, I use:
我有一个大文本文件,我想查看"time spent"此文本文件中包含的行,我使用:
grep -in "time spent" myfile.txt
But I'm interested only in the lines after 50000. In the output I want to see lines after 50000 and that contain "time spent". Is there a way to do this?
但我只对 50000 之后的行感兴趣。在输出中,我想看到 50000 之后的行并且包含“花费的时间”。有没有办法做到这一点?
采纳答案by adray
You can tail it, then grep:
你可以拖尾,然后 grep:
tail -n +50000 myfile.txt | grep -in "time spent"
回答by neric
Alternatively you can use sed.
sedcan be used to mimic greplike this:
或者,您可以使用sed.
sed可以用来模仿grep这样的:
sed -n 's/pattern/&/p'
sed -n 's/pattern/&/p'
By default sedprints every line even if no substitution occurs. The combinations of -nand /pmakes sedprint only the lines where a substitution has occured. Finally, we replace patternby &which means replace patternby itself. Result: we just mimicked grep.
默认情况下,sed即使没有发生替换,也会打印每一行。-n和/pmake的组合sed仅打印发生替换的行。最后,我们replace patternby &which 意思是replacepattern自己。结果:我们只是模仿了grep.
Now sedcan take a range of lines on which to act. In your case:
现在sed可以采取一系列行动。在你的情况下:
sed -n '50000,$s/time spent/&/p' myfile.txt
sed -n '50000,$s/time spent/&/p' myfile.txt
The format to specify the range is as follow: start,endWe just instruct sed to work from line 50000 to $which means last line.
指定范围的格式如下:start,end我们只是指示 sed 从第 50000 行到$最后一行。
回答by don_crissti
You could use head+ grepand group commands with {...}so that they share the same input:
您可以使用head+grep和 group 命令,{...}以便它们共享相同的输入:
{ head -n 50000 >/dev/null; grep -i PATTERN; } < infile
headdoesn't consume the whole input, it gets only the first 50000 lines and dumps them to /dev/null; the remaining lines are processed by grep.
If you need the line numbers prepended (like with grep -in) you could use awk:
head不消耗整个输入,它只获取前 50000 行并将它们转储到/dev/null; 其余行由 处理grep。
如果您需要预先添加行号(例如 with grep -in),您可以使用awk:
awk 'NR>50000 && tolower(Using sed and grep:
sed -n '1,50000p' someFile | grep < your_string >
)~/PATTERN/{print NR ": " ##代码##}' infile
回答by K.K
Answer for grepping between any 2 line numbers:
任何 2 个行号之间的 grepping 的答案:
##代码##
