bash 打印最后匹配的行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17298106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:46:41  来源:igfitidea点击:

Print last matching line?

bashawk

提问by Steven Penny

Using awk, I would like to print the last matching line of a file. I would like only the matching line itself, not any range of lines. I can use a command like this

使用awk,我想打印文件的最后匹配行。我只想要匹配的行本身,而不是任何范围的行。我可以使用这样的命令

awk '/foo/' bar.txt

However this will print all matching lines, not just the last one.

但是,这将打印所有匹配的行,而不仅仅是最后一行。

回答by fedorqui 'SO stop harming'

You can save the value in a variable and then print it after processing the whole file:

您可以将值保存在变量中,然后在处理整个文件后打印它:

awk '/foo/ {a=
$ cat file
foo1
foo2
foo3
4
5
$ awk '/foo/ {a=
awk '/foo/' bar.txt | tail -1
} END{print a}' file foo3
} END{print a}' file

Test

测试

sed -n '/foo/h;$!b;g;p' bar.txt

回答by Ignacio Vazquez-Abrams

The command tailallows you to retreive the last nlines of an input stream. You can pipe your awkoutput into tailin order to trim off everything except the last line:

该命令tail允许您检索n输入流的最后几行。您可以通过管道将awk输出导入tail以修剪除最后一行之外的所有内容:

tac file | awk '/foo/ {print; exit}'

回答by jaypal singh

sedsolution:

sed解决方案:

##代码##

Place the matching regexin hold buffer and branch out. Keep doing this until end of file. When the end of file is reached, grab the line from hold space and place it on pattern space. Print pattern space.

将匹配regex放在保持缓冲区中并分支出来。继续这样做直到文件结束。当到达文件末尾时,从保持空间中抓取该行并将其放置在模式空间中。打印模式空间。

回答by glenn Hymanman

reverse the file and find the firstmatch.

反转文件并找到第一个匹配项。

##代码##