且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何获取从最后匹配到文件结尾的行?

更新时间:2022-06-25 16:54:58

实际上,您可以使用 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 .