Skip site navigation (1)Skip section navigation (2)
Date:      Mon, 4 Sep 2023 17:22:32 +0200
From:      Andreas Kusalananda =?utf-8?B?S8OkaMOkcmk=?= <andreas.kahari@abc.se>
To:        questions@freebsd.org
Subject:   Re: cut off last lines of a document
Message-ID:  <ZPX2ODLfz4azBzSt@harpo.local>
In-Reply-To: <86edjet336.fsf@ltc.des.no>
References:  <57be5495-97f8-4f22-9ae2-cd9712596e64@nebelschwaden.de> <uy2fdgobbejnhyctyyrbhgvhutuhtbzzxwg5wukdujyhw7h25u@74ujfxm5gjlk> <CAMtcK2qbc1jQHXJ%2Bwu0F62o6aDQKYAx3kYARuQFZLHS6DJktRg@mail.gmail.com> <a9b64c1d-02a6-45c1-aaed-85e4cf622776@nebelschwaden.de> <86edjet336.fsf@ltc.des.no>

next in thread | previous in thread | raw e-mail | index | archive | help
Sorry, this is resent due to a misconfiguration of my mail client.

On Mon, Sep 04, 2023 at 04:39:25PM +0200, Dag-Erling Smørgrav wrote:
> Ede Wolf <listac@nebelschwaden.de> writes:
> > Am 03.09.23 um 23:16 schrieb paul beard:
> > > export COUNT=`wc -l /var/log/messages | tr -d -c '\n[:digit:]'` #
> > > export WANT=`echo "$COUNT-3" | bc ` # subtract 3 (or however many)
> > > head -$WANT /var/log/messages # display the remainder.
> 
> 1) there is no need to export the variables
> 2) don't use backticks, use $() instead
> 3) if you use 'wc -l <foo' instead of 'wc -l foo' you don't need tr
> 3b) alternatively, use read: wc -l foo | read COUNT FILENAME
> 4) the shell can do the math for you: 'head -$((COUNT-3)) foo'
> 
> > Thanks, but the problem I currently see here, as with the suggestion
> > of Archimedes earlier, I am currently not easily able to convert this
> > into a feed from stdin.
> 
> Pipe-friendly pure shell solution:
> 
> drop_last_three() {
>         local a b c d
>         read a
>         read b
>         read c
>         while read d ; do
>                 echo "$a"
>                 a="$b"
>                 b="$c"
>                 c="$d"
>         done
> }
> 
> DES
> -- 
> Dag-Erling Smørgrav - des@FreeBSD.org

Note how this will handle backslash-escaped newlines in the input, and
that, depending on the shell and its configuration, the "echo" call may
or may not expand backslash-escaped characters in the input (e.g. "\n"
and "\t").  The "echo" may also interpret the string "-n" as an option
it occurs on its own line.  You may also lose flanking whitespace.

-- 
Andreas (Kusalananda) Kähäri
SciLifeLab, NBIS, ICM
Uppsala University, Sweden

.



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?ZPX2ODLfz4azBzSt>