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: Sami Kerola
Subject: Re: How to count the last line when it does not end with a newline character?
Date: Tue, 7 Sep 2021 16:42:56 +0100

On Tue, 7 Sept 2021 at 11:35, Bernhard Voelker <mail@bernhard-voelker.de> wrote:
> On 9/5/21 07:37, 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
>
> A text file (in contrast to a binary file) must end on a newline character,
> otherwise the remainder after the last '\n' in the file is not an entire line.
>
> And that's what wc(1) effectively does (and says so in its man page):
>
>   wc - print newline, word, and byte counts for each file
>   ___________^^^^^^^_________________^^^^^^
>
> If you'd like to treat the remainder as a line, then you have to add
> a newline character at the end.
>
>   $ printf 'a\nb\n' | wc -l
>   2

Maybe it is worth to mention that the wc(1) is counting lines POSIX correctly.
Number of the lines is number of valid lines, excluding incomplete lines.

3.206 Line

A sequence of zero or more non- <newline> characters plus a
terminating <newline> character.

3.195 Incomplete Line

A sequence of one or more non- <newline> characters at the end of the file.

Above definitions are from the web page below.
https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html

-- 
Sami Kerola
http://www.iki.fi/kerolasa/



reply via email to

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