grep -A1 'blah' logfile

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


当前回答

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.

其他回答

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可以输出行号(-n)。通过<num>:和<num>-,匹配和下一行之间的输出是不同的:

# grep -A1 -n '230 Login successful."$' /var/log/vsftpd.log
1:Sat Nov  5 03:29:43 2022 [pid 10] [foo] FTP response: Client "10.1.1.1", "230 Login successful."
2-Sat Nov  5 03:29:43 2022 [pid 10] [foo] FTP response: Client "10.1.1.1", "221 Goodbye."
3:Sat Nov  5 04:44:41 2022 [pid 10] [foo] FTP response: Client "10.1.1.1", "230 Login successful."
4-Sat Nov  5 04:44:42 2022 [pid 10] [foo] FTP response: Client "10.1.1.1", "221 Goodbye."

这样我们就可以过滤输出,只得到每个匹配的下一行:

# grep -A1 -n '230 Login successful."$' /var/log/vsftpd.log | grep -E "^[0-9]+-" | cut -d"-" -f2-
Sat Nov  5 03:29:43 2022 [pid 10] [foo] FTP response: Client "10.1.1.1", "221 Goodbye."
Sat Nov  5 04:44:42 2022 [pid 10] [foo] FTP response: Client "10.1.1.1", "221 Goodbye."

Perl一行程序警告

只是为了好玩……匹配后只打印一行

perl -lne '$. == $next && print; $next = ($.+1) if /match/' data.txt

更有趣的是……匹配后打印接下来的十行

perl -lne 'push @nexts, (($.+1)..($.+10)) if /match/; $. ~~ @nexts && print' data.txt

虽然有点作弊,因为实际上有两个命令

滚边是你的朋友……

使用grep -A1显示匹配后的下一行,然后将结果管道到tail,只抓取一行,

cat logs/info.log | grep "term" -A1 | tail -n 1

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

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