匹配模式后提取第N行 [英] Extract Nth line after matching pattern
问题描述
我想在使用 grep
, awk
或匹配模式之后提取第N行> sed
。
例如我有这样一段文字:
版本:
60000< br />
我想提取60000个。
我尝试了 Revision:([a-z0-9] *)\s *([0-9]){5}
但是当我将它传递给grep时: grep Revision:([a-z0-9] *)\s *([0-9]){5} file.html
我什么都没得到。
我该如何做到这一点?
要在匹配模式之后提取第N行,您需要:
$ b $ pre $ code awk'c&&! - c; / pattern / {c = N}'文件
例如
awk 'c&&! - c; / Revision:/ {c = 5}'档案
将会在文本Revision:后打印第5行。/.
仅供参考下面的习语描述了如何选择给定特定模式匹配的记录范围: p>
a)打印所有记录:
awk'/ pattern / {f = 1} f'文件
b)以某种模式打印所有记录:
awk'f; / pattern / {f = 1}'文件
c)在某些模式后打印第N条记录:
awk' d)c&&&打印除第N条记录以外的所有记录a awk'c&&! - c {next} / pattern / {c = N} 1 '文件
e)在某些模式后打印N条记录:
awk'c& c - ; / pattern / {c = N}'文件
$ b $ f)在某些模式后打印除N条记录以外的每条记录:
awk'c&& c - {next} / pattern / {c = N} 1'file
awk'/ pattern / {c = N} c&& amp;& amp;& amp; ; c--'file
我将变量名称从f改为found c表示适当的count,因为这更能表达变量实际是什么。
I want to extract the Nth line after a matching pattern using grep
, awk
or sed
.
For example I have this piece of text:
Revision:
60000<br />
And I want to extract 60000.
I tried Revision:([a-z0-9]*)\s*([0-9]){5}
which matches the Revision together with the revision number but when I pass it to grep: grep Revision:([a-z0-9]*)\s*([0-9]){5} file.html
I get nothing.
How can I achieve this?
解决方案 To extract the Nth line after a matching pattern
you want:
awk 'c&&!--c;/pattern/{c=N}' file
e.g.
awk 'c&&!--c;/Revision:/{c=5}' file
would print the 5th line after the text "Revision:"/.
FYI the following idioms describe how to select a range of records given a specific pattern to match:
a) Print all records from some pattern:
awk '/pattern/{f=1}f' file
b) Print all records after some pattern:
awk 'f;/pattern/{f=1}' file
c) Print the Nth record after some pattern:
awk 'c&&!--c;/pattern/{c=N}' file
d) Print every record except the Nth record after some pattern:
awk 'c&&!--c{next}/pattern/{c=N}1' file
e) Print the N records after some pattern:
awk 'c&&c--;/pattern/{c=N}' file
f) Print every record except the N records after some pattern:
awk 'c&&c--{next}/pattern/{c=N}1' file
g) Print the N records from some pattern:
awk '/pattern/{c=N}c&&c--' file
I changed the variable name from "f" for "found" to "c" for "count" where appropriate as that's more expressive of what the variable actually IS.
这篇关于匹配模式后提取第N行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!