bash 如何grep最后一次出现的线条图案

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24014194/
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-10 00:51:49  来源:igfitidea点击:

How to grep the last occurrence of a line pattern

bashshellawksedgrep

提问by user3702858

I have a file with contents

我有一个包含内容的文件

x
a
x
b
x
c

I want to grep the last occurrence,

我想 grep 最后一次出现,

x
c

when I try

当我尝试

sed -n  "/x/,/b/p" file

it lists all the lines, beginning xto c.

它列出了所有的线,开始xc

回答by steffen

I'm not sure if I got your question right, so here are some shots in the dark:

我不确定我的问题是否正确,所以这里有一些黑暗中的镜头:

  • Print last occurence of x(regex):

    grep x file | tail -1
    
  • Alternatively:

    tac file | grep -m1 x
    
  • Print file from first matching line to end:

    awk '/x/{flag = 1}; flag' file
    
  • Print file from last matching line to end (prints all lines in case of no match):

    tac file | awk '!flag; /x/{flag = 1};' | tac
    
  • 打印x(正则表达式)的最后一次出现:

    grep x file | tail -1
    
  • 或者:

    tac file | grep -m1 x
    
  • 从第一个匹配行到结尾打印文件:

    awk '/x/{flag = 1}; flag' file
    
  • 从最后一个匹配行到结尾打印文件(在不匹配的情况下打印所有行):

    tac file | awk '!flag; /x/{flag = 1};' | tac
    

回答by potong

This might work for you (GNU sed):

这可能对你有用(GNU sed):

sed '/x/h;//!H;$!d;x' file

Saves the last xand what follows in the hold space and prints it out at end-of-file.

将最后一个x和后面的内容保存在保留空间中,并在文件末尾打印出来。

回答by elig

grep -A 1 x file | tail -n 2

-A 1tells grep to print one line after a match line
with tailyou get the last two lines.

-A 1告诉 grep 在匹配行之后打印一行,
tail获得最后两行。

or in a reversed way:

或以相反的方式:

tac fail | grep -B 1 x -m1 | tac

Note: You should make sure your pattern is "strong" enough so it gets you the right lines. i.e. by enclosing it with ^at the start and $at the end.

注意:您应该确保您的模式足够“强大”,以便为您提供正确的线条。即通过^在开始和$结束时将其括起来。

回答by ray

not sure how to do it using sed, but you can try awk

不确定如何使用sed,但您可以尝试awk

awk '{a=a"\n"##代码##; if (##代码## == "x"){ a=##代码##}}  END{print a}' file