如何获取从最后一场比赛到文件末尾的行? [英] How to get lines from the last match to the end of file?

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

问题描述

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

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='(^|
)MARKER
' 'END{printf "%s", $0}' file
jjj
kkk
lll

说明:

  • 您通过 RS='(^| )MARKER ' 将记录分隔符定义为 (^| )MARKER ,默认情况下它是 EOL 字符
  • 'END{printf "%s", $0}' => 在文件末尾,打印整行,因为 RS 设置为 (^| )MARKER , $0 将包含直到 EOF 的所有行.
  • You define your record separator as (^| )MARKER via RS='(^| )MARKER ', 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 (^| )MARKER , $0 will include all the lines until EOF.

<小时>另一种选择是使用 grep (GNU):

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

说明:

  • -z 使用 ASCII NUL 字符作为分隔符
  • -o 只打印匹配的
  • -P 激活 perl 模式
  • PCRE 正则表达式:(?<=MARKER )(?:(?!MARKER)[^])+ 在这里解释 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 )(?:(?!MARKER)[^])+ 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天全站免登陆