coreutils
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to count the last line when it does not end with a newline chara


From: Carl Edquist
Subject: Re: How to count the last line when it does not end with a newline character?
Date: Tue, 7 Sep 2021 06:47:54 -0500 (CDT)
User-agent: Alpine 2.23.2 (DEB 496 2020-07-19)

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

[Prev in Thread] Current Thread [Next in Thread]