我想从文件中读取file.txt索引n低于与给定正则表达式匹配的行的所有行regex.例如文件
hello my friend
foo
_bar_
I love this bar
poof
kouki
splash in the water
bar
Run Code Online (Sandbox Code Playgroud)
如果regex=bar和n=2,那么我们想读
hello my friend
foo
kouki
Run Code Online (Sandbox Code Playgroud)
我找到了解决这个问题的方法
sed -n `grep -n bar file.txt | awk -F ":" '{print ($1 - 2)}' | tr '\n' 'X'
| sed 's+X+p;+g' | sed 's/.$//'` < file.txt
Run Code Online (Sandbox Code Playgroud)
是否有更好(更快,更容易阅读)的解决方案?
(我对这个问题的目标纯粹是教育性的)
用awk:
$ awk '/bar/ && FNR>2 {print li[-2]}
{li[-2]=li[-1]; li[-1]=$0}' file
hello my friend
foo
kouki
Run Code Online (Sandbox Code Playgroud)
其可以由更一般的打印Ñ 个匹配线之前(而不必在存储器中具有整个文件):
$ awk -v n=3 '/bar/ && FNR>n{ print li[n]}
{for (i=n;i>1;i--)
li[i]=li[i-1]
li[1]=$0}' file
hello my friend
poof
Run Code Online (Sandbox Code Playgroud)