grep -A1 'blah' logfile

多亏了这个命令,每一行都有'blah',我得到了包含'blah'的行输出和日志文件中的下一行。这可能是一个简单的,但我找不到一种方法来省略一行有'blah',只显示下一行在输出。


当前回答

到目前为止,对于这个问题已经给出了许多很好的答案,但我仍然错过了一个awk没有使用getline的答案。因为,在一般情况下,没有必要使用getline,我将使用:

awk ' f && NR==f+1; /blah/ {f=NR}' file  #all matches after "blah"

or

awk '/blah/ {f=NR} f && NR==f+1' file   #matches after "blah" not being also "blah"

逻辑始终包括存储找到“blah”的行,然后打印后面一行的行。

Test

示例文件:

$ cat a
0
blah1
1
2
3
blah2
4
5
6
blah3
blah4
7

取“blah”后面的所有行。如果出现在第一个之后,则打印另一个“blah”。

$ awk 'f&&NR==f+1; /blah/ {f=NR}' a
1
4
blah4
7

获取“blah”之后的所有行,如果这些行本身不包含“blah”。

$ awk '/blah/ {f=NR} f && NR==f+1' a
1
4
7

其他回答

reaim的回答很好,对我很有用。将其扩展到打印模式之后的第7行是很简单的

awk -v lines=7 '/blah/ {for(i=lines;i;--i)getline; print $0 }' logfile

我不知道有什么方法可以用grep来做到这一点,但是使用awk可以达到相同的结果:

awk '/blah/ {getline;print}' < logfile

grep /Pattern/ | tail -n 2 | head -n

尾先2个,头最后一个,比赛结束后正好排在第一行。

you can use grep, then take lines in jumps: grep -A1 'blah' logfile | awk 'NR%3==2' you can also take n lines after match, for example: seq 100 | grep -A3 .2 | awk 'NR%5==4' 15 25 35 45 55 65 75 85 95 explanation - here we want to grep all lines that are *2 and take 3 lines after it, which is *5. seq 100 | grep -A3 .2 will give you: 12 13 14 15 -- 22 23 24 25 -- ... the number in the modulo (NR%5) is the added rows by grep (here it's 3 by the flag -A3), +2 extra lines because you have current matching line and also the -- line that the grep is adding.

如果你想坚持使用grep:

grep -A1 'blah' logfile | grep -v "blah"

或者使用sed:

sed -n '/blah/{n;p;}' logfile