如何在匹配线之前提取存在2行的行?

时间:2012-07-19 08:55:07

标签: parsing text sed awk grep

我有一个很大的unix文本文件,我想获得在匹配行上方3行的行。

我该怎么做?

注意我不想让它们介于两者之间。因此,如果文本是

one
two
three
four

我正在寻找字符串'three',我想得到输出

one

而不是

one
two
three

3 个答案:

答案 0 :(得分:1)

使用awk
http://www.gnu.org/software/gawk/manual/html_node/Array-Basics.html#Array-Basics

awk -v n=3 '{s[NR%n]=$0} /three/{print s[(NR-n+1)%n]}' foo.txt

答案 1 :(得分:0)

将grep与以下选项一起使用

   -A NUM, --after-context=NUM
          Print NUM lines of trailing context after matching lines.  Places a line containing -- between contiguous groups of matches.


   -B NUM, --before-context=NUM
          Print NUM lines of leading context before matching lines.  Places a line containing -- between contiguous groups of matches.

因此,根据您的要求,使用命令:

grep -B 3 three <filename>

答案 2 :(得分:0)

这是一个:首先grep你正在寻找的单词,上下两行:

$ grep -B 2

给出:

one
two
three
--
one
two
three
--
one
two
three
(...)

然后使用sed打印每四行:

$ grep -B 2 three test.txt |sed -n '1~4'p

(从这里得到sed部分:http://www.thegeekstuff.com/2009/09/unix-sed-tutorial-printing-file-lines-using-address-and-patterns/