如何获取从最后匹配到文件结尾的行? [英] How to get lines from the last match to the end of file?

查看:42
本文介绍了如何获取从最后匹配到文件结尾的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要在最后一次匹配到文件末尾之后打印行.比赛的数量可以是任意的,而不是确定的.我有一些文字,如下所示.

Need to print lines after the last match to the end of file. The number of matches could be anything and not definite. I have some text as shown below.

MARKER
aaa
bbb
ccc
MARKER
ddd
eee
fff
MARKER
ggg
hhh
iii
MARKER
jjj
kkk
lll

期望的输出是

jjj
kkk
lll

我可以将awk与RS和FS一起使用以获得所需的输出吗?

Do I use awk with RS and FS to get the desired output?

推荐答案

实际上,您可以使用 awk (gawk)进行操作,而无需使用任何管道.

You can actually do it with awk (gawk) without using any pipe.

$ awk -v RS='(^|\n)MARKER\n' 'END{printf "%s", $0}' file
jjj
kkk
lll

说明:

  • 您可以通过 RS ='(^ | \ n)MARKER \ n'将记录分隔符定义为(^ | \ n)MARKER \ n ,默认情况下是是 EOL char
  • 'END {printf%s",$ 0}' =>在文件末尾,您将整行打印出来,因为 RS 设置为(^ | \ n)MARKER \ n $ 0 将包括所有行,直到EOF.
  • You define your record separator as (^|\n)MARKER\n via RS='(^|\n)MARKER\n', by default it is the EOL char
  • 'END{printf "%s", $0}' => at the end of the file, you print the whole line, as RS is set at (^|\n)MARKER\n, $0 will include all the lines until EOF.


另一种选择是使用 grep (GNU):

$ grep -zoP '(?<=MARKER\n)(?:(?!MARKER)[^\0])+\Z' file
jjj
kkk
lll

说明:

  • -z 使用ASCII NUL字符作为分隔符
  • -o 仅打印匹配项
  • -P 激活perl模式
  • PCRE正则表达式:(?< = MARKER \ n)(?:( ?! MARKER)[^ \ 0])+ \ Z 在这里 https://regex101.com/r/RpQBUV/2/
  • -z to use the ASCII NUL character as delimiter
  • -o to print only the matching
  • -P to activate the perl mode
  • PCRE regex: (?<=MARKER\n)(?:(?!MARKER)[^\0])+\Z explained here https://regex101.com/r/RpQBUV/2/


最后但并非最不重要的是,还可以使用以下 sed 方法:

sed -n '/^MARKER$/{n;h;b};H;${x;p}' file
jjj
kkk
lll

说明:

  • n 跳至下一行
  • h 用当前行替换保留空间
  • H 进行相同的操作,但不要替换,而是添加
  • 文件交换结束时
  • $ {x; p} ( x )保留空间和模式空间并打印( p )
  • n jump to next line
  • h replace the hold space with the current line
  • H do the same but instead of replacing, append
  • ${x;p} at the end of the file exchange (x) hold space and pattern space and print (p)

可以变成:

tac file |  sed -n '/^MARKER$/q;p' | tac

如果我们使用 tac .

这篇关于如何获取从最后匹配到文件结尾的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆