如何获取包含\n的最后一行?

How to get the last line that contains \n?

根据定义,一行必须以换行符 (\n) (ref.) 结尾。但是出于这个 post 的目的,我会将任何一系列字符视为一行,无论它是否以 \n.

结尾

命令tail -n 1 returns最后一行不管是否以\n结尾。如何从文件中获取以 \n 结尾的最后一行,无论该行是文件的最后一行还是倒数第二行?

cat -vte file|grep "$$"|tail -1

这个呢?或者使用 cat -vte

的其他方式

这样多余的 $ 将被删除:

echo -en "Enter\nEnter again\nNo enter this time"|cat -vte|grep "$$"|sed 's/$$//g'|tail -1

+1 linux 的变体(Perl 正则表达式,正面前瞻断言,仅显示匹配部分):

echo -en "Enter\nEnter again\nNo enter this time"|cat -vte|grep -Po ".*(?=\$$)"|tail -1

这是您可以使用 Perl 实现的一种方法:

perl -ne '$s = $_ if /\n$/ }{ print $s' file

脚本逐行读取文件的每一行,如果以\n结尾,则赋值给变量$s。读取文件后,将打印 $s 。如果最后一行没有以换行结束,那么将打印倒数第二行,如下所示:

$ cat file
first line
second
third$ perl -ne '$s = $_ if /\n$/ }{ print $s' file
second

请注意,我故意留在 $ 中以显示提示,由于缺少换行符,提示位于文件最后一行的末尾。