Soo...如果包含与pattern 匹配的内容,您想在匹配foo 的内容和匹配] 的内容之间打印一个部分,对吗?那么
sed -n '/foo/ { :a; N; /\]/!ba /pattern/ p }' filename
sed 代码的工作原理如下:
/foo/ { # if a line matches foo
:a # jump label
N # fetch the next line and append it to the pattern space
/\]/! ba # if the result does not match ] (that is, if the last fetched
# line does not contain something that matches ]), go back to :a
/pattern/ p # if in all these lines, there is something that matches the
# pattern, print them
}
使匹配在前面不贪心——也就是说,如果在一个文件中
1
foo
2
foo
3
pattern
4
]
5
匹配应包括3 和4 但不包括2,脚本可以这样修改(或类似,取决于您要使用的模式):
sed -n '/foo/ { :a; N; /\n[^\n]*foo/ s/.*\n//; /\]/!ba /pattern/ p }' filename
如果该行中的某些内容与 foo 匹配,/\n[^\n]*foo/ s/.*\n// 将删除最后获取行之前的所有内容。
如果您的图案是线条图案(即,如果它们包含^ 或$),则需要对其进行修改。一旦模式空间中存在多行,^ 将匹配模式空间的开头和$ 的结尾,而不是一行。然后,您可以使用 \n 来匹配行尾。例如,如果您想在精确为 foo 和 ] 的行之间进行非贪婪匹配(如果它们之间存在精确为 pattern 的行),您可以使用
sed -n '/^foo$/ { :a; N; /\nfoo$/ s/.*\n//; /\n\]$/!ba /\npattern\n/ p }' filename