Search code examples
regexbashfilenewlinetail

How to get the last line that contains \n?


By definition a line must end with newline character (\n) (ref.). But for the purpose of this post, I will consider any series of characters as a line whether or not it finishes with \n.

The command tail -n 1 returns the last line whether or not it ends with \n. How can one get from a file the last line that ends with \n whether or not this line is the last line or the second-to-last line of the file?


Solution

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

    What about this? Or some other way with cat -vte

    This way the extra $ will be removed:

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

    +1 variant for linux (Perl regexp, positive look-ahead assertion, show matched part only):

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