Hi Peng,

On Sun, 5 Sep 2021, Peng Yu wrote:

I got 1 instead of 2 in the following example. How to count the last even when it does not end with a newline character? Thanks.

$ printf 'a\nb'|wc -l
1

Here is a little trick.

You can append a newline if/when missing to the end of input with:

        sed '$a\'

So for your example:

        $ printf 'a\nb' | sed '$a\' | wc -l
        2

        $ printf 'a\nb\n' | sed '$a\' | wc -l
        2


You can apply this to a bunch of files at once also, with potentially missing newlines in their final lines:

        $ sed '$a\' *.txt


Note this is not the same as

        $ cat *.txt | sed '$a\'

which will only add a missing newline once to the end of the entire input.


Hope that helps,

Carl

Reply via email to