grep -A1 'blah' logfile
多亏了这个命令,每一行都有'blah',我得到了包含'blah'的行输出和日志文件中的下一行。这可能是一个简单的,但我找不到一种方法来省略一行有'blah',只显示下一行在输出。
grep -A1 'blah' logfile
多亏了这个命令,每一行都有'blah',我得到了包含'blah'的行输出和日志文件中的下一行。这可能是一个简单的,但我找不到一种方法来省略一行有'blah',只显示下一行在输出。
当前回答
您可以尝试使用awk:
awk '/blah/{getline; print}' logfile
其他回答
您可以尝试使用awk:
awk '/blah/{getline; print}' logfile
你可以匹配多行,然后输出n行:
awk 'c&&!--c;/match1/{c=1};/match2/{c=2}' file
匹配多个项目,输出n行后:
#!/bin/sh
[ -z $3 ] && echo $0 file \[match n\]+... \# to output line n after match && exit
f=$1; shift; while [ \! -z $2 ]; do s="$s/$1/{c=$2};"; shift; shift; done
awk 'c&&!--c;'$s $f
所以你可以把上面的文件保存为match .sh和chmod +x match .sh,然后如果你有一个这样的文件:
line1
line2
line3
line4
line5
line6
line7
并运行:
./matchn.sh file line1 1 line3 2 line6 1
你会得到:
line2
line5
line7
这将需要更多的调整来支持0偏移量。
如果你想坚持使用grep:
grep -A1 'blah' logfile | grep -v "blah"
或者使用sed:
sed -n '/blah/{n;p;}' logfile
我不知道有什么方法可以用grep来做到这一点,但是使用awk可以达到相同的结果:
awk '/blah/ {getline;print}' < logfile
使用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."