我有一个大的 unix 文本文件,我想获取匹配行上方存在 3 行的行。
我怎样才能做到这一点?
注意我不想在两者之间找到界限。因此,如果文本是
one
two
three
four
我正在寻找字符串“三”,我想作为输出
one
并不是
one
two
three
使用 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
使用带有以下选项的 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>
这里有一个:首先 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/