【发布时间】:2014-10-07 10:33:06
【问题描述】:
我昨天开始学习 awk,试图解决这个问题(并学习一种有用的新语言)。起初我尝试使用 sed,但很快意识到它不是访问/操作模式匹配之前的行的正确工具。
我需要:
- 删除所有包含“foo”的行(它本身很简单,但在跟踪之前的行时不是这样)
- 查找包含“bar”的行
- 删除包含“bar”的行之前的行
- 删除包含“bar”的行之后的所有行,直到我们到达一个空行
示例输入:
This is foo stuff
I like food!
It is tasty!
stuff
something
stuff
stuff
This is bar
Hello everybody
I'm Dr. Nick
things
things
things
期望的输出:
It is tasty!
stuff
something
stuff
things
things
things
我的尝试:
{
valid=1; #boolean variable to keep track if x is valid and should be printed
if ($x ~ /foo/){ #x is valid unless it contains foo
valid=0; #invalidate x so that is doesn't get printed at the end
next;
}
if ($0 ~ /bar/){ #if the current line contains bar
valid = 0; #x is invalid (don't print the previous line)
while (NF == 0){ #don't print until we reach an empty line
next;
}
}
if (valid == 1){ #x was a valid line
print x;
}
x=$0; #x is a reference to the previous line
}
超级奖励积分(不需要解决我的问题,但我有兴趣了解如何完成):
- 能够在模式匹配之前删除 n 行
- 在输出中包含/排除空行的选项
【问题讨论】: