grep -A1 'blah' logfile
多亏了这个命令,每一行都有'blah',我得到了包含'blah'的行输出和日志文件中的下一行。这可能是一个简单的,但我找不到一种方法来省略一行有'blah',只显示下一行在输出。
grep -A1 'blah' logfile
多亏了这个命令,每一行都有'blah',我得到了包含'blah'的行输出和日志文件中的下一行。这可能是一个简单的,但我找不到一种方法来省略一行有'blah',只显示下一行在输出。
当前回答
总的来说,我同意您在这里要求使用大量grep,而另一种工具可能是更好的解决方案。但是在嵌入式环境中,我可能不希望使用sed或awk来完成此操作。我发现以下解决方案是有效的(只要它们不是连续的匹配):
grep -A1 AT\+CSQ wvdial.out | grep -v AT\+CSQ
基本上,匹配它们,为每个匹配附加一行上下文,然后通过原始模式的反向匹配来将它们剥离出来。当然,这意味着您可以假设您的模式不会出现在“下一行”中。
其他回答
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并没有那么复杂,我认为你想要提升awk作为这项工作的工具:
Awk '/blah/ {getline;打印$0}的日志文件
如果你有任何问题让我知道,我认为它很值得学习一点awk,它是一个伟大的工具:)
附注:这个例子并没有获得“无用使用猫奖”;) http://porkmail.org/era/unix/award.html
总的来说,我同意您在这里要求使用大量grep,而另一种工具可能是更好的解决方案。但是在嵌入式环境中,我可能不希望使用sed或awk来完成此操作。我发现以下解决方案是有效的(只要它们不是连续的匹配):
grep -A1 AT\+CSQ wvdial.out | grep -v AT\+CSQ
基本上,匹配它们,为每个匹配附加一行上下文,然后通过原始模式的反向匹配来将它们剥离出来。当然,这意味着您可以假设您的模式不会出现在“下一行”中。
你可以匹配多行,然后输出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 -A1显示匹配后的下一行,然后将结果管道到tail,只抓取一行,
cat logs/info.log | grep "term" -A1 | tail -n 1